自己整理了 spring boot 结合 Redis 的工具类
引入依赖
org.springframework.boot spring-boot-starter-data-redis
加入配置
# Redis数据库索引(默认为0) spring.redis.database=0 # Redis服务器地址 spring.redis.host=localhost # Redis服务器连接端口 spring.redis.port=6379
实现代码
这里用到了 静态类工具类中 如何使用 @Autowired
package com.lmxdawn.api.common.utils;
import java.util.Collection;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
@Component
public class CacheUtils {
@Autowired
private RedisTemplate redisTemplate;
// 维护一个本类的静态变量
private static CacheUtils cacheUtils;
@PostConstruct
public void init() {
cacheUtils = this;
cacheUtils.redisTemplate = this.redisTemplate;
}
public static void set(String key, String value) {
cacheUtils.redisTemplate.opsForValue().set(key, value);
}
public static void set(String key, String value, Long timeout) {
cacheUtils.redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
}
public static Object get(String key) {
return cacheUtils.redisTemplate.opsForValue().get(key);
}
public static boolean expire(String key, Long ttl) {
return cacheUtils.redisTemplate.expire(key, ttl, TimeUnit.SECONDS);
}
public static boolean hasKey(String key) {
return cacheUtils.redisTemplate.hasKey(key);
}
public static Long sAdd(String key, String... value) {
return cacheUtils.redisTemplate.opsForSet().add(key, value);
}
public static Set sGetMembers(String key) {
return cacheUtils.redisTemplate.opsForSet().members(key);
}
public static Boolean zAdd(String key, String value, double score) {
return cacheUtils.redisTemplate.opsForZSet().add(key, value, score);
}
public static Double zScore(String key, String value) {
return cacheUtils.redisTemplate.opsForZSet().score(key, value);
}
public static Boolean delete(String key) {
return cacheUtils.redisTemplate.delete(key);
}
public static Long delete(Collection keys) {
return cacheUtils.redisTemplate.delete(keys);
}
}
相关地址
GitHub 地址:https://github.com/lmxdawn/vue-admin-java
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



