当前位置 博文首页 > java_bird:Spring boot redis的使用(二)
Spring boot redis的使用(二)
看过我第一篇介绍spring boot redis的文章的同行们可能发现了一个问题,那就是redis中的value并没有设置过期时间,之前我也是为这个苦恼了半天,发现现成的注解并没有提供过期时间的相关入口,后来经过各种搜索终于找到了解决方法,本篇我们就来介绍如何设置过期时间。
过期时间的设置目前我找到了两个方法:1.通过redis管理器集中配置不同区域下的过期时间;2.通过扩展redis管理器来进行额外传参的方式进行设置,好了废话不多说直接上代码。
1.通过redis管理器集中配置不同区域下的过期时间
2.通过扩展redis管理器来进行额外传参的方式进行设置
2.1编写redis管理器(RedisCacheManager)的扩展类并继承RedisCacheManager,具体代码如下
package com.zxl.examples.catche;
import org.springframework.cache.Cache;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.core.RedisOperations;
/**
* Created by Administrator on 2017/7/25.
*/
public class RedisCacheManagerExtend extends RedisCacheManager {
public RedisCacheManagerExtend(RedisOperations redisOperations) {
super(redisOperations);
}
/**
* 缓存参数的分隔符
* 数组元素0=缓存的名称
* 数组元素1=缓存过期时间TTL
* 数组元素2=缓存在多少秒开始主动失效来强制刷新
*/
private String separator = "#";
/**
* 缓存主动在失效前强制刷新缓存的时间
* 单位:秒
*/
private long preloadSecondTime=0;
@Override
public Cache getCache(String name) {
String[] cacheParams=name.split(this.getSeparator());
String cacheName = cacheParams[0];
if(cacheName==null || "".equals(cacheName.trim())){
return null;
}
Long expirationSecondTime = this.computeExpiration(cacheName);
if(cacheParams.length>1) {
expirationSecondTime=Long.parseLong(cacheParams[1]);
this.setDefaultExpiration(expirationSecondTime);
}
if(cacheParams.length>2) {
this.setPreloadSecondTime(Long.parseLong(cacheParams[2]));
}
Cache cache = super.getCache(cacheName);
if(null==cache){
return null;
}
return cache;
// logger.info("expirationSecondTime:"+expirationSecondTime);
// CustomizedRedisCache redisCache= new CustomizedRedisCache(
// cacheName,
// (this.isUsePrefix() ? this.getCachePrefix().prefix(cacheName) : null),
// this.getRedisOperations(),
// expirationSecondTime,
// preloadSecondTime);
// return redisCache;
}
public String getSeparator() {
return separator;
}
public void setSeparator(String separator) {
this.separator = separator;
}
public long getPreloadSecondTime() {
return preloadSecondTime;
}
public void setPreloadSecondTime(long preloadSecondTime) {
this.preloadSecondTime = preloadSecondTime;
}
}
cs