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);
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。