共计 1201 个字符,预计需要花费 4 分钟才能阅读完成。
Spring Cache @Cacheable 本身不支持 key expiration 的设置,以下代码可自定义实现 Spring Cache 的 expiration,针对 Redis、SpringBoot2.0。
直接上代码:
@Service
@Configuration
public class CustomCacheMng{
private Logger logger = LoggerFactory.getLogger(this.getClass());
// 指明自定义 cacheManager 的 bean name
@Cacheable(value = “test”,key = “‘obj1′”,cacheManager = “customCacheManager”)
public User cache1(){
User user = new User().setId(1);
logger.info(“1”);
return user;
}
@Cacheable(value = “test”,key = “‘obj2′”)
public User cache2(){
User user = new User().setId(1);
logger.info(“2”);
return user;
}
// 自定义的 cacheManager,实现存活 2 天
@Bean(name = “customCacheManager”)
public CacheManager cacheManager(
RedisTemplate<?, ?> redisTemplate) {
RedisCacheWriter writer = RedisCacheWriter.lockingRedisCacheWriter(redisTemplate.getConnectionFactory());
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofDays(2));
return new RedisCacheManager(writer, config);
}
// 提供默认的 cacheManager,应用于全局
@Bean
@Primary
public CacheManager defaultCacheManager(
RedisTemplate<?, ?> redisTemplate) {
RedisCacheWriter writer = RedisCacheWriter.lockingRedisCacheWriter(redisTemplate.getConnectionFactory());
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
return new RedisCacheManager(writer, config);
}
}