Spring Cache的注解方式上枕,@Cacheable
, @CachePut
和 @CacheEvict
組合用起來(lái)真的很方便椅棺,比直接使用Jedis的接口簡(jiǎn)潔太多含滴。
但是诱渤,問(wèn)題來(lái)了,@Cacheable
不支持指定過(guò)期時(shí)間谈况,也有叫TTL的勺美。
啥递胧??赡茸?
Oh,my god!!!
這簡(jiǎn)直讓人抓狂6衅ⅰ!坛掠!
Spring Cache這么優(yōu)秀的框架不應(yīng)該犯這種低級(jí)的錯(cuò)誤赊锚,連最基本的特性都不支持。
一頓百度Google屉栓,原來(lái)是Spring Cache背后支持了很多廠商提供的Cache舷蒲,不同的Cache對(duì)expire的支持不盡相同,現(xiàn)在還不能做到一個(gè)簡(jiǎn)單的expire字段就能配置好友多。
可能的解決方案:
- 自己實(shí)現(xiàn)@Cachable注解牲平, 略復(fù)雜
- 設(shè)置Schedule,要注意一個(gè)Cache里面有多個(gè)Key的問(wèn)題
@CacheEvict(allEntries = true, value = {GAMES})
@Scheduled(fixedDelay = 10 * 60 * 1000 , initialDelay = 500)
public void reportCacheEvict() {
System.out.println("Flush Cache " + dateFormat.format(new Date()));
}
- 自己配置一個(gè)CacheManager域滥, 其中可以給指定名稱(chēng)的Cache指定expireTime
很明顯纵柿,第三種方案,比較簡(jiǎn)單快捷启绰,而且兼容性好昂儒。
自定義CacheManager 的代碼:
public CacheManager cacheManager() {
RedisCacheManager redisCacheManager =newRedisCacheManager(redisTemplate());
redisCacheManager.setTransactionAware(true);
redisCacheManager.setLoadRemoteCachesOnStartup(true);
redisCacheManager.setUsePrefix(true);
//配置緩存的過(guò)期時(shí)間
Mapexpires =newHashMap();
expires.put("token",expiration);
redisCacheManager.setExpires(expires);
returnredisCacheManager;
}
參考文章
http://blog.csdn.net/huanghongfei1/article/details/61195650