您的位置:首页 > 数据库 > Redis

使用spring-data-redis做缓存

2015-12-18 10:56 676 查看
说到缓存,首先肯定是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) {
...
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: