配置starter,当前boot版本2.5.3
1、引入依赖pom.xml:
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.4.2</version>
</dependency>
2、配置yml
spring
redis:
database: 0
host: 127.0.0.1
port: 6379
password: lizhenfeng
lettuce:
pool:
max-active: 20
max-wait: -1
max-idle: 10
min-idle: 0
# 哨兵设置
#sentinel:
#master:
#nodes:
timeout: 3000
3、创建redis配置类,没想到这个的作用...如果说是设置序列化,emmm,对象序列化一直是失败,很恼火,然后直接使用了字符串
/**
* 2022年11月27日01:21:22 redis配置
*
* @author Administrator
*/
@EnableCaching
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer =
new GenericJackson2JsonRedisSerializer();
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// 设置value的序列化规则和 key的序列化规则
redisTemplate.setKeySerializer(stringRedisSerializer);
redisTemplate.setValueSerializer(stringRedisSerializer);
redisTemplate.setHashKeySerializer(stringRedisSerializer);
redisTemplate.setHashValueSerializer(genericJackson2JsonRedisSerializer);
redisTemplate.setDefaultSerializer(genericJackson2JsonRedisSerializer);
redisTemplate.setEnableDefaultSerializer(true);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
4、创建RedisService和实现类RedisServiceImpl,不知是从哪位大神那里拿来的了,很多方法没用到没改,最后自己加了两个方法,因为list存直接存报转换异常,然后对象存也有缓存异常,心累就没改,直接是把list里面的对象转成字符串进行设值,emmm,没有试过直接将list转成字符串存,但是估计不报错的把握应该不小
/**
* redis接口
*
* @author Administrator
*/
public interface RedisService {
/** 缓存的有效时长 **/
long TIME_ONE_SECOND = 1;
long TIME_ONE_MINUTE = 60 * TIME_ONE_SECOND;
long TIME_ONE_HOUR = 60 * TIME_ONE_MINUTE;
long TIME_ONE_DAY = 24 * TIME_ONE_HOUR;
long TIME_ONE_MONTH = 30 * TIME_ONE_DAY;
/**
* 获取缓存剩余时间
*
* @param keys
* @return 秒
*/
long getExpire(String... keys);
/**
* 缓存数据 并 设置有效期
*
* @param value
* @param exp
* @param unit
* @param keys
* @param <V>
* @return
*/
<V> boolean setByKey(V value, long exp, TimeUnit unit, String... keys);
/**
* 缓存数据 并 设置有效期(默认时间单位为秒)
*
* @param value
* @param exp
* @param keys
* @param <V>
* @return
*/
<V> boolean setByKey(V value, long exp, String... keys);
/**
* 缓存数据(默认存储一个月)
*
* @param value
* @param keys
* @param <V>
* @return
*/
<V> boolean setByKey(V value, String... keys);
/**
* incr key 原子递增
*
* @param key
* @param value
* @return
*/
long increment(String key, long value);
/**
* incr key 原子递增
*
* @param key
* @param value
* @param exp
* @return
*/
long increment(String key, long value, long exp);
/**
* rpush = right push (rpush key value) 添加元素到List集合的尾部(默认存储时间单位为秒)
*
* @param key
* @param value 一个元素 或 一个List集合
* @param exp
* @param <V>
* @return
*/
<V> boolean rpush(String key, V value, long exp);
/**
* lpush = left push (lpush key value) 添加元素到List集合的头部(默认存储时间单位为秒)
*
* @param key
* @param value 一个元素 或 一个List集合
* @param exp
* @param <V>
* @return
*/
<V> boolean lpush(String key, V value, long exp);
/**
* lrange = list range (lrange key 0 -1 即获取全部列表数据) 获取List集合数据
*
* @param key
* @param <V>
* @return
*/
<V> V lrange(String key);
/**
* sadd key value 添加元素到Set集合(默认存储时间单位为秒)
*
* @param key
* @param value 一个元素 或 一个Set集合
* @param exp
* @param <V>
* @return
*/
<V> boolean sadd(String key, V value, long exp);
/**
* smembers key 获取Set集合数据
*
* @param key
* @param <V>
* @return
*/
<V> V smembers(String key);
/**
* zadd key score value (score为有序索引序列) 添加元素到ZSet集合(有序)(默认存储时间单位为秒)
*
* @param key
* @param value 一个元素 或 一个Set集合
* @param exp
* @param <V>
* @return
*/
<V> boolean zadd(String key, V value, long exp);
/**
* zrange key 0 -1 获取ZSet集合数据
*
* @param key
* @param <V>
* @return
*/
<V> V zrange(String key);
/**
* 获取Redis缓存数据
*
* @param keys
* @param <V>
* @return
*/
<V> V getByKey(String... keys);
/**
* 删除Redis缓存数据
*
* @param keys
* @return
*/
boolean delByKey(String... keys);
/**
* 通过 Redis 发布订阅消息
*
* @param channel
* @param message
*/
void convertAndSend(String channel, Object message);
/**
* 自定义存list集合
*
* @param list
* @param key
*/
void setListCustom(List<?> list, String key);
/**
* 自定义取list集合
*
* @param key
* @param clazz
* @return
*/
List getListCustom(String key, Class clazz);
}
/**
* 2022年11月27日14:06:52 redis实现类
*
* @author Administrator
*/
@Slf4j
@Service
public class RedisServiceImpl implements RedisService {
private RedisTemplate<String, Object> redisTemplate;
/**
* 拼接缓存数据的key
*
* @param keys
* @return
*/
private String getMemKey(String... keys) {
if (keys == null || keys.length == 0) {
return null;
}
if (keys.length == 1) {
return keys[0];
}
StringBuffer memKey = new StringBuffer();
Arrays.stream(keys).forEach(key -> {
memKey.append(":");
memKey.append(key);
});
return memKey.toString().replaceFirst(":", "");
}
/**
* 设置缓存有效期
*
* @param key
* @param exp 默认一个月
* @param unit 默认为秒
* @return
*/
private boolean expireByKey(String key, long exp, TimeUnit unit) {
if (exp == 0) {
exp = RedisService.TIME_ONE_MONTH;
}
if (unit == null) {
unit = TimeUnit.SECONDS;
}
return this.redisTemplate.expire(key, exp, unit);
}
@Override
public long getExpire(String... keys) {
String memKey = this.getMemKey(keys);
Long expire = this.redisTemplate.getExpire(memKey);
log.info("获取缓存数据剩余有效期:key-{}, value-{}", memKey, expire);
return expire == null ? 0 : expire;
}
@Override
public <V> boolean setByKey(V value, long exp, TimeUnit unit, String... keys) {
String memKey = this.getMemKey(keys);
this.redisTemplate.opsForValue().set(memKey, value);
return this.expireByKey(memKey, exp, unit);
}
@Override
public <V> boolean setByKey(V value, long exp, String... keys) {
return setByKey(value, exp, TimeUnit.SECONDS, keys);
}
@Override
public <V> boolean setByKey(V value, String... keys) {
return setByKey(value, 0, keys);
}
@Override
public long increment(String key, long value) {
// 永不过期
return this.redisTemplate.opsForValue().increment(key, value);
}
@Override
public long increment(String key, long value, long exp) {
long afterIncrementValue = this.redisTemplate.opsForValue().increment(key, value);
this.expireByKey(key, exp, TimeUnit.SECONDS);
return afterIncrementValue;
}
@Override
public <V> boolean rpush(String key, V value, long exp) {
this.redisTemplate.opsForList().rightPush(key, value);
return this.expireByKey(key, exp, TimeUnit.SECONDS);
}
@Override
public <V> boolean lpush(String key, V value, long exp) {
this.redisTemplate.opsForList().leftPush(key, value);
return this.expireByKey(key, exp, TimeUnit.SECONDS);
}
@Override
public <V> V lrange(String key) {
log.debug("获取缓存数据:key-{}", key);
return (V)this.redisTemplate.opsForList().range(key, 0, -1);
}
@Override
public <V> boolean sadd(String key, V value, long exp) {
this.redisTemplate.opsForSet().add(key, value);
return this.expireByKey(key, exp, TimeUnit.SECONDS);
}
@Override
public <V> V smembers(String key) {
log.debug("获取缓存数据:key-{}", key);
return (V)this.redisTemplate.opsForSet().members(key);
}
@Override
public <V> boolean zadd(String key, V value, long exp) {
this.redisTemplate.opsForZSet().add(key, value, Math.random());
return this.expireByKey(key, exp, TimeUnit.SECONDS);
}
@Override
public <V> V zrange(String key) {
log.debug("获取缓存数据:key-{}", key);
return (V)this.redisTemplate.opsForZSet().range(key, 0, -1);
}
@Override
@SuppressWarnings("unchecked")
public <V> V getByKey(String... keys) {
String memKey = this.getMemKey(keys);
V value = (V)this.redisTemplate.opsForValue().get(memKey);
log.info("获取缓存数据:key-{}, value-{}", memKey, JSON.toJSONString(value));
return value;
}
@Override
public boolean delByKey(String... keys) {
return this.redisTemplate.opsForValue().getOperations().delete(this.getMemKey(keys));
}
@Override
public void convertAndSend(String channel, Object message) {
this.redisTemplate.convertAndSend(channel, message);
}
@Override
public void setListCustom(List<?> list, String key) {
if (!CollectionUtils.isEmpty(list) && list.size() > 0) {
list.forEach(v -> {
this.rpush(key, JSONObject.toJSONString(v), 0);
});
}
}
@Override
public List getListCustom(String key, Class clazz) {
List list = new ArrayList<>();
List<String> ls = this.lrange(key);
ls.forEach(s -> {
list.add(JSONObject.parseObject(s, clazz));
});
return list;
}
@Autowired
public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
}
5、使用
private RedisService redisService;
@Autowired
public void setRedisService(RedisService redisService) {
this.redisService = redisService;
}
@Override
public SysVariable getByKey(String sysVariableKey) {
SysVariable sysVariable = this.redisService.getByKey(sysVariableKey);
if (sysVariable == null) {
sysVariable = this.sysVariableMapper.getByKey(sysVariableKey);
this.redisService.setByKey(sysVariable, sysVariableKey);
}
return sysVariable;
}
@Override标签:return,String,笔记,redis,value,param,key,exp From: https://www.cnblogs.com/lizhenfeng/p/17161654.html
public List<UserInfo> structLoginInfo(Long roleId) {
String key = roleId == null ? "structLoginInfo" : "structLoginInfo_" + roleId;
List<UserInfo> userInfoList;
if (roleId != null) {
// 根据roleId构建
}
// 目测第一次会有空指针异常,但是时间紧迫不想重启redis服务了
userInfoList = (List<UserInfo>)this.redisService.getListCustom(key, UserInfo.class);
if (CollectionUtils.isEmpty(userInfoList) || userInfoList.size() == 0) {
userInfoList = this.personMapper.structLoginInfo();
this.redisService.setListCustom(userInfoList, key);
return userInfoList;
}
return userInfoList;
}