Springboot RedisCacheManager 类的配置 指定key的过期时间 并在配置文件里配置
目的&效果
在springBoot中配置了RedisCache,当使用@Cacheable注解时,默认为redisCache,通过在配置文件里设置不同key的过期时间,达到可自定义key过期时间的效果。
方案
step 1
新建一个Map类,用于存放要设置的key
@ConfigurationProperties
public class Properties {
private final Map<String, Duration> initCaches = Maps.newHashMap();
public Map<String, Duration> getInitCaches() {
return initCaches;
}
}
step2
在redis配置类里编写cacheManager,并将map set进去
@Autowired
private Properties properties;
@Bean
public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(10)).disableCachingNullValues();
RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory);
ImmutableSet.Builder<String> cacheNames = ImmutableSet.builder();
ImmutableMap.Builder<String, RedisCacheConfiguration> cacheConfig = ImmutableMap.builder();
for (Map.Entry<String, Duration> entry : properties.getInitCaches().entrySet()) {
cacheNames.add(entry.getKey());
cacheConfig.put(entry.getKey(), defaultCacheConfig.entryTtl(entry.getValue()));
}
return RedisCacheManager.builder(redisCacheWriter)
.cacheDefaults(defaultCacheConfig)
.initialCacheNames(cacheNames.build())
.withInitialCacheConfigurations(cacheConfig.build())
.build();
}
step3
在Springboot yml文件里配置相关的key的过期时间 就可以指定@Cacheable的value的过期时间
//伪代码
@Cacheable(cacheNames = "fooboo", key = "#xxx", unless = "#result == null")
public void fooboo(String xxx){}
applicaion.yml文件中设置
initCaches:
fooboo: 10m
fooboo1: 1h
则在redis缓存中fooboo的值,10分钟过期,fooboo1的值1小时过期
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。