在使用spring cache时,可以选择RedissonSpringCacheManager作为缓存底层实现,在redisson官方文档有详细说明
Redisson提供了将Redis无缝整合到Spring框架的能力。Redisson依照Spring Cache标准提供了基于Redis的Spring缓存实现。 每个缓存(Cache)实例都提供了了两个重要的可配置参数:过期时间(ttl)和最长空闲时间(maxIdleTime),如果这两个参数都未指定或值为0,那么实例管理的数据将永久保存。 配置范例:
@Configuration
@ComponentScan
@EnableCaching
public static class Application {
@Bean(destroyMethod="shutdown")
RedissonClient redisson() throws IOException {
Config config = new Config();
config.useClusterServers()
.addNodeAddress("127.0.0.1:7004", "127.0.0.1:7001");
return Redisson.create(config);
}
@Bean
CacheManager cacheManager(RedissonClient redissonClient) {
Map<String, CacheConfig> config = new HashMap<String, CacheConfig>();
// 创建一个名称为"testMap"的缓存,过期时间ttl为24分钟,同时最长空闲时maxIdleTime为12分钟。
config.put("testMap", new CacheConfig(24*60*1000, 12*60*1000));
return new RedissonSpringCacheManager(redissonClient, config);
}
}
- 可以单独为某个key设置过期时间
- 不设置过期时间会永久保存
过期时间实现方式
上述代码中单独指定了testMap的过期时间,需要注意的是此时若使用redis查看工具或命令行,查询testMap的ttl的值是-1,-1的意思是说不会过期。
redisson实现过期的方式是会创建一个以redisson__idle__set和redisson__timeout__set开头的key,分别保存testMap的最大空闲时间和过期时间,例:disson__timeout__set:{testMap},底层会有定时任务和线程去执行过期判断,如下图
不设置过期时间永久保存
没有单独配置的key默认是永久保存的,个人感觉这样不太好,首先数据会越来越多,其次个人感觉缓存应该是有保质期的。解决方法也很简单,自定义一个类,继承RedissonSpringCacheManager,重写里面的createDefaultConfig,默认生成有有过期时间的config即可,如下图
此时没有添加到配置里的key创建config时,会使用一个1小时过期的配置。