Spring Cache的注解方式,@Cacheable
, @CachePut
和 @CacheEvict
组合用起来真的很方便,比直接使用Jedis的接口简洁太多。
但是,问题来了,@Cacheable
不支持指定过期时间,也有叫TTL的。
啥???
Oh,my god!!!
这简直让人抓狂!!!
Spring Cache这么优秀的框架不应该犯这种低级的错误,连最基本的特性都不支持。
一顿百度Google,原来是Spring Cache背后支持了很多厂商提供的Cache,不同的Cache对expire的支持不尽相同,现在还不能做到一个简单的expire字段就能配置好。
可能的解决方案:
- 自己实现@Cachable注解, 略复杂
- 设置Schedule,要注意一个Cache里面有多个Key的问题
@CacheEvict(allEntries = true, value = {GAMES})
@Scheduled(fixedDelay = 10 * 60 * 1000 , initialDelay = 500)
public void reportCacheEvict() {
System.out.println("Flush Cache " + dateFormat.format(new Date()));
}
- 自己配置一个CacheManager, 其中可以给指定名称的Cache指定expireTime
很明显,第三种方案,比较简单快捷,而且兼容性好。
自定义CacheManager 的代码:
public CacheManager cacheManager() {
RedisCacheManager redisCacheManager =newRedisCacheManager(redisTemplate());
redisCacheManager.setTransactionAware(true);
redisCacheManager.setLoadRemoteCachesOnStartup(true);
redisCacheManager.setUsePrefix(true);
//配置缓存的过期时间
Mapexpires =newHashMap();
expires.put("token",expiration);
redisCacheManager.setExpires(expires);
returnredisCacheManager;
}
参考文章
http://blog.csdn.net/huanghongfei1/article/details/61195650
网友评论