本文转载自:https://www.cnblogs.com/a565810497/p/10937477.html
之前尝试了一下springboot集成springcahce:https://www.cnblogs.com/a565810497/p/10931426.html
又尝试了用guava设置springcahce的有效时长:https://www.cnblogs.com/a565810497/p/10932149.html
但是终究觉得不太灵活,因为guava设置有效时长只是设置默认的,不能设置多个,而且springcahce不是缓存在数据库上的,那么redis就很适合和springcahce集合起来
首先我们要使用springcahce集成redis先,参考文章:https://blog.battcn.com/2018/05/13/springboot/v2-cache-redis/
添加依赖
在porm.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>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
属性配置
## Redis服务器地址 spring.redis.host=127.0.0.1 ## Redis服务器连接端口 spring.redis.port=6379 ## Redis服务器连接密码(默认为空) spring.redis.password= # 一般来说是不用配置的,Spring Cache 会根据依赖的包自行装配 spring.cache.type=redis # 连接超时时间(毫秒) spring.redis.timeout=10000 # Redis默认情况下有16个分片,这里配置具体使用的分片 spring.redis.database=0 # 连接池最大连接数(使用负值表示没有限制) 默认 8 spring.redis.lettuce.pool.max-active=8 # 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1 spring.redis.lettuce.pool.max-wait=-1 # 连接池中的最大空闲连接 默认 8 spring.redis.lettuce.pool.max-idle=8 # 连接池中的最小空闲连接 默认 0 spring.redis.lettuce.pool.min-idle=0
然后我们就可以基于redis设置springcache的有效时间了,参考文章:https://blog.csdn.net/weixin_42047790/article/details/84189275
在启动类配置有效时长:
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
return new RedisCacheManager(
RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory),
this.getRedisCacheConfigurationWithTtl(30*60), // 默认策略,未配置的 key 会使用这个
this.getRedisCacheConfigurationMap() // 指定 key 策略
);
}
private Map<String, RedisCacheConfiguration> getRedisCacheConfigurationMap() {
Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>();
//DayCache和SecondsCache进行过期时间配置
redisCacheConfigurationMap.put("DayCache", this.getRedisCacheConfigurationWithTtl(24*60*60));
redisCacheConfigurationMap.put("SecondsCache", this.getRedisCacheConfigurationWithTtl(2));
return redisCacheConfigurationMap;
}
private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer seconds) {
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
redisCacheConfiguration = redisCacheConfiguration.serializeValuesWith(
RedisSerializationContext
.SerializationPair
.fromSerializer(jackson2JsonRedisSerializer)
).entryTtl(Duration.ofSeconds(seconds));
return redisCacheConfiguration;
}
@Bean
public KeyGenerator wiselyKeyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append("." + method.getName());
if(params==null||params.length==0||params[0]==null){
return null;
}
String join = String.join("&", Arrays.stream(params).map(Object::toString).collect(Collectors.toList()));
String format = String.format("%s{%s}", sb.toString(), join);
//log.info("缓存key:" + format);
return format;
}
};
}
分别使用不同时长的cache:
@Override
@Cacheable(value = "SecondsCache")
public TestTime getTestTime(){
return new TestTime(new Date());
}
@Override
@Cacheable(value = "DayCache")
public TestTime getTestTime1(){
return new TestTime(new Date());
}
Secondscache是设置了2秒的生命周期。
DayCache是设置了一天的生命周期。
为什么要那么繁琐的设置呢,其实redis已经可以在添加缓存的时候设置有效时间,但是我们是想用注解的方式 @cacheable 做到不需要代码侵入来实现注解,于是就结合redis和springcahce。
