說到緩存,首先確定是spring-cache了.html
spring-cache使用一個CacheManager來進行管理緩存,爲了使用咱們的redis做爲緩存源,須要向spring註冊一個CacheManagerredis
@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.htmlspring
咱們都知道spring-cache是不可以在註解上配置過時時間的,那麼如何本身定義每一個緩存的過時時間呢。緩存
首先有個方法叫作:setDefaultExpiration,這裏能夠設置一個默認的過時時間。this
其次還有一個setExpires方法:spa
public void setExpires(Map<String, Long> expires) { this.expires = (expires != null ? new ConcurrentHashMap<String, Long>(expires) : null); }
其接受一個Map類型,key爲緩存的value,value爲longcode
好比在Map中put一個htm
map.put("AccountCache",1000L);
那麼全部的AccountCache的緩存過時時間爲1000秒blog
@Cacheable(value = "AccountCache", key = "T(com.morequ.usercenter.util.ConfigurationPropertys).ACCOUNTFINDBYID+#id") public Account findById(long id) { ... }