使用spring-data-redis做缓存

时间:2023-03-09 03:54:06
使用spring-data-redis做缓存

说到缓存,首先肯定是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) {
...
}