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/也只是提到Supportfor 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)); }
相关文章推荐
- Spring Boot Cache + redis 设置有效时间和自动刷新缓存,时间支持在配置文件中配置
- Spring Boot缓存实战 Redis 设置有效时间和自动刷新缓存-2
- SpringBoot注解缓存配置浅析(Redis集群)
- [置顶] 在Springboot上使用jedis来操作缓存redis --jedis的配置
- spring-boot整合redis作为缓存(1)——redis的设置
- 使用 Spring data redis 结合 Spring cache 缓存数据配置
- spring-boot 结合spring-data-redis使用redis的消息队列
- spring boot redis注解缓存。
- Redis整合Spring结合使用缓存实例
- 第十四章 springboot + profile(不同环境读取不同配置)
- 35. Spring Boot集成Redis实现缓存机制【从零开始学Spring Boot】
- redis+spring注解方式实现配置缓存时间过期
- Spring Boot 整合 Redis 实现缓存操作
- (35)Spring Boot集成Redis实现缓存机制【从零开始学Spring Boot】
- Spring Boot 整合 Redis 实现缓存操作
- SpringBoot 整合redis实现缓存 记录@CachePut值为1
- 1 Springboot中使用redis,自动缓存、更新、删除
- 学习SpringBoot+Redis 实现页面缓存
- Spring Boot + Mybatis + 二级缓存实例(Ehcache,Redis)
- spring boot 在不同环境下读取不同配置文件的一种方式