Springboot RedisCacheManager 类的配置 指定key的过期工夫 并在配置文件里配置
目标&成果
在springBoot中配置了RedisCache,当应用@Cacheable注解时,默认为redisCache,通过在配置文件里设置不同key的过期工夫,达到可自定义key过期工夫的成果。
计划
step 1
新建一个Map类,用于寄存要设置的key
@ConfigurationPropertiespublic class Properties { private final Map<String, Duration> initCaches = Maps.newHashMap(); public Map<String, Duration> getInitCaches() { return initCaches; }}
step2
在redis配置类里编写cacheManager,并将map set进去
@Autowiredprivate Properties properties; @Beanpublic 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小时过期