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

redis结合springboot设置不同缓存失效配置

2017-10-10 18:02 846 查看

redis 设置多个缓存不同时间失效 (JAVA) 

先说问题,在使用Spring Data Redis时,先设置不同cacheName 或者 key 的失效时间。官方文档中https://docs.spring.io/spring-data/redis/docs/2.0.0.RELEASE/reference/html/也只是提到Support
for Spring Cache Abstraction,并没有实际的案例。网上有的也是命令行的操作(大家都知道)。没办法,看文档中cache 也只提到了RedisCacheMaager这个类,那么只能看看能不能在它上面做做文章。下面是他的几个属性。



使用过redis的童鞋一定会对expires这个单词敏感,因为设置缓存失效时间经常用到,下面我们就看看这个集合在哪里被用到。

protected RedisCache createCache(String cacheName) {
long expiration = this.computeExpiration(cacheName);
return new RedisCache(cacheName, this.usePrefix?this.cachePrefix.prefix(cacheName):null, this.redisOperations, expiration);
}

protected long computeExpiration(String name) {
Long expiration = null;
if(this.expires != null) {
expiration = (Long)this.expires.get(name);
}

return expiration != null?expiration.longValue():this.defaultExpiration;
}


我们可以看到computeExpiration这个方法中对其进行了使用。createCashe这个方法根据cacheName进行创建。
当然这个类也提供设置casheNames的方法。
public void setCacheNames(Collection<String> cacheNames) {
Object newCacheNames = CollectionUtils.isEmpty(cacheNames)?Collections.emptySet():new HashSet(cacheNames);
this.configuredCacheNames = (Set)newCacheNames;
this.dynamic = ((Set)newCacheNames).isEmpty();
}


这时我们的路就越来越清晰了。只要配置自己的RedisCasheManager。方法也很简单。

@Configuration
//@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 3600 * 12)
@EnableCaching
public class RedisAutoConfig extends CachingConfigurerSupport {

@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
//设置缓存过期时间
Map<String, Long> expires = new HashMap<>();
expires.put("12h",3600 * 12L);
expires.put("1h",3600 * 1L);
expires.put("10m",60 * 5L);
rcm.setExpires(expires);
//        rcm.setDefaultExpiration(60 * 60 * 12);//秒
return rcm;
}

这样我们就定义了3个不同失效时间的cache。(key=12h,失效时间12个小时)
然后通过@Cacheable注解就可以很方便的使用了。

@Cacheable(value = "12h", keyGenerator = "keyGenerator")
public PagingResultDTO<YearlySalesDto> queryYearlySales(@RequestBody SalesOrderQuery query) {
PageHelper.startPage(query.getPageNum(), query.getPageSize());
return MybatisPaginationUtil.paginationResult(salesOrderDao.queryYearlySales(query));
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息