說到緩存,首先肯定是spring-cache了.
spring-cache使用一個CacheManager來進行管理緩存,為了使用我們的redis作為緩存源,需要向spring注冊一個CacheManager
@Bean(name = "redisCacheManager") public CacheManager cacheManager(@SuppressWarnings("rawtypes") RedisTemplate redisTemplate) throws IOException { RedisCacheManager manage = new RedisCacheManager(redisTemplate); log.info("redis 默認過期時間 {} 秒", redisDefaultExpiration);
//這里可以設置一個默認的過期時間 manage.setDefaultExpiration(redisDefaultExpiration); manage.setExpires(this.loadFromConfig()); return manage; }
具體redisTemplate請參考上一篇:http://www.cnblogs.com/lic309/p/5056248.html
我們都知道spring-cache是不能夠在注解上配置過期時間的,那么如何自己定義每個緩存的過期時間呢。
首先有個方法叫做:setDefaultExpiration,這里可以設置一個默認的過期時間。
其次還有一個setExpires方法:
public void setExpires(Map<String, Long> expires) { this.expires = (expires != null ? new ConcurrentHashMap<String, Long>(expires) : null); }
其接受一個Map類型,key為緩存的value,value為long
比如在Map中put一個
map.put("AccountCache",1000L);
那么所有的AccountCache的緩存過期時間為1000秒
@Cacheable(value = "AccountCache", key = "T(com.morequ.usercenter.util.ConfigurationPropertys).ACCOUNTFINDBYID+#id") public Account findById(long id) {
...
}
