Spring boot 初学

Spring Cache注解不支持expire的问题

2017-08-19  本文已影响2268人  挨踢的懒猫

Spring Cache的注解方式,@Cacheable, @CachePut@CacheEvict组合用起来真的很方便,比直接使用Jedis的接口简洁太多。

但是,问题来了,@Cacheable不支持指定过期时间,也有叫TTL的。

啥???
Oh,my god!!!
这简直让人抓狂!!!

Spring Cache这么优秀的框架不应该犯这种低级的错误,连最基本的特性都不支持。

一顿百度Google,原来是Spring Cache背后支持了很多厂商提供的Cache,不同的Cache对expire的支持不尽相同,现在还不能做到一个简单的expire字段就能配置好。

可能的解决方案:

@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 的代码:

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

上一篇 下一篇

猜你喜欢

热点阅读