一 : spring cache 配置 基于 redis
1: 添加pom依赖
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.6.0.RELEASE</version>
</dependency>
2:配置文件指定缓存使用redis
spring:
cache:
type: redis
3:RedisCacheManager配置
/**
* 可以自动设置失效时间的RedisCacheManager
* 失效时间设置规则 @Cacheable(cacheNames = "redisKey(10)S")
* (为cacheNames 与自定义失效时间的分隔符
* )为失效时间值与单位的分隔符
*
* @Author sjf
* @Date 2021/01/21
**/
@Slf4j
public class ExpireTimeRedisCacheManager extends RedisCacheManager {
protected ExpireTimeRedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration) {
super(cacheWriter, defaultCacheConfiguration);
}
/**
* 生成缓存配置
* @param name 设置的缓存名称(完整配置的例子users#10_SECONDS)
* @param cacheConfig redis缓存配置
* @return
*/
@Override
protected RedisCache createRedisCache(String name, RedisCacheConfiguration cacheConfig) {
name = GoodsRedisConst.PREFIX.concat(name);
if (StringUtils.isBlank(name)) {
return super.createRedisCache(name, cacheConfig);
}
String[] nameSplits = name.split(GoodsRedisConst.NAME_TIME_CONFIG_SEPARATOR);
if (ArrayUtils.isNotEmpty(nameSplits) && 1 == nameSplits.length) {
log.info("get default ttl unit mills {}", cacheConfig.getTtl());
return super.createRedisCache(name, cacheConfig);
}
String finalName = nameSplits[0];
String ttlTimeConfig = nameSplits[1];
String[] ttlTimeConfigSplits = ttlTimeConfig.split(GoodsRedisConst.TTL_TIME_SEPARATOR);
if (ArrayUtils.isEmpty(ttlTimeConfigSplits) || 2 != ttlTimeConfigSplits.length) {
log.info("ttl time config {} is invalid!", ttlTimeConfig);
return super.createRedisCache(finalName, cacheConfig);
}
try {
Long time = Long.parseLong(ttlTimeConfigSplits[0]);
TimeUnit timeUnit = getTimeUnitByName(ttlTimeConfigSplits[1].toUpperCase());
Duration ttl = getAndAddRandomSeconds(time, timeUnit);
RedisCacheConfiguration newTtlRedisCacheConfiguration = cacheConfig.entryTtl(ttl);
return super.createRedisCache(finalName, newTtlRedisCacheConfiguration);
} catch (Exception e) {
log.warn("get ttl time config error!", e);
}
return super.createRedisCache(finalName, cacheConfig);
}
/**
* 时间单位转换
* @param name
* @return
*/
private TimeUnit getTimeUnitByName(String name){
if ("d".equals(name) || "D".equals(name)){
return TimeUnit.DAYS;
}else if ("h".equals(name) || "H".equals(name)){
return TimeUnit.HOURS;
}else if ("m".equals(name) || "M".equals(name)){
return TimeUnit.MINUTES;
}else if ("s".equals(name) || "S".equals(name)){
return TimeUnit.SECONDS;
}else {
return TimeUnit.SECONDS;
}
}
/**
* 获取ttl失效时间并且随机增加毫秒数
* @param time 时间 time
* @param timeUnit 单位 unit
* @return
*/
public Duration getAndAddRandomSeconds(Long time, TimeUnit timeUnit) {
long seconds;
switch (timeUnit) {
case SECONDS:
seconds = time;
break;
case MILLISECONDS:
seconds = TimeUnit.MILLISECONDS.toSeconds(time);
break;
case HOURS:
seconds = TimeUnit.HOURS.toSeconds(time);
break;
case MINUTES:
seconds = TimeUnit.MINUTES.toSeconds(time);
break;
case DAYS:
seconds = TimeUnit.DAYS.toSeconds(time);
break;
default:
seconds = TimeUnit.SECONDS.toSeconds(time);
break;
}
// 随机增加失效秒数,避免同一时间集体失效
long secondsWithRandom = seconds + GoodsRedisConst.EXPIRE_RANDOM.nextInt(100);
return Duration.ofSeconds(secondsWithRandom);
}
}
4:指定 key的生成策略,全局异常处理 redisTemplate配置cacheManager配置
/**
* @author sjf
* @description
* @date 2021/1/21
**/
@Configuration
@Slf4j
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisCacheAutoConfiguration extends CachingConfigurerSupport {
/**
* redis FastJson序列化
*/
@Bean
@ConditionalOnMissingBean(value = RedisSerializer.class)
public RedisSerializer<Object> redisSerializer() {
return new GenericFastJsonRedisSerializer();
}
/**
* 设置自定义序列化的RedisTemplate
*
* @param redisConnectionFactory
* @param redisSerializer 序列化
* @return
*/
@Bean
@ConditionalOnMissingBean(RedisTemplate.class)
public RedisTemplate<String, Object> redisTemplate(@Autowired RedisConnectionFactory redisConnectionFactory,
@Autowired RedisSerializer<Object> redisSerializer) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
// key,hash key使用String序列化
RedisSerializer<String> stringRedisSerializer = RedisSerializer.string();
template.setValueSerializer(fastJsonRedisSerializer);
template.setKeySerializer(stringRedisSerializer);
// value,hash value设置FastJson序列化
template.setHashValueSerializer(fastJsonRedisSerializer);
template.setHashKeySerializer(stringRedisSerializer);
template.setConnectionFactory(redisConnectionFactory);
return template;
}
/**
* 配置 spring cache manager RedisCacheManager
*/
@Bean
@ConditionalOnMissingBean(value = CacheManager.class)
public CacheManager cacheManager(@Autowired RedisConnectionFactory redisConnectionFactory) {
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
// 设置缓存的默认过期时间
config = config.entryTtl(Duration.ofSeconds(GoodsRedisConst.DEFAULT_TIME))
// 不缓存空值
.disableCachingNullValues();
RedisCacheManager cacheManager = new ExpireTimeRedisCacheManager(
RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory), config);
return cacheManager;
}
/**
* 重写key的生成策略()
* @return
*/
@Bean
@ConditionalOnMissingBean(KeyGenerator.class)
@Override
public KeyGenerator keyGenerator() {
return (o, method, objects) -> {
StringBuilder stringBuilder = new StringBuilder();
/**
* //获取类目类目
* stringBuilder.append(o.getClass().getSimpleName());
* stringBuilder.append(".");
* //获取方法名
* stringBuilder.append(method.getName());
* stringBuilder.append(":");
*/
//请求参数数组
for (Object obj : objects) {
if (obj != null && obj.toString().contains("=")) {
HashMap<String, Object> hashMap = JSON.parseObject(JSON.toJSONString(obj), HashMap.class);
hashMap.forEach((k, v) -> {
stringBuilder.append(k + ":" + v + ":");
});
}else {
stringBuilder.append(obj + ":");
}
}
StringBuilder redisKey = stringBuilder.deleteCharAt(stringBuilder.length() - 1);
log.info("redisKey============{}",redisKey);
return redisKey;
};
}
/**
* redis数据操作异常处理 这里的处理:在日志中打印出错误信息,但是放行
* 保证redis服务器出现连接等问题的时候不影响程序的正常运行,使得能够出问题时不用缓存
* @return
*/
@Bean
@Override
public CacheErrorHandler errorHandler() {
CacheErrorHandler cacheErrorHandler = new CacheErrorHandler() {
@Override
public void handleCachePutError(RuntimeException exception, Cache cache,
Object key, Object value) {
RedisErrorException(exception, key);
}
@Override
public void handleCacheGetError(RuntimeException exception, Cache cache,
Object key) {
RedisErrorException(exception, key);
}
@Override
public void handleCacheEvictError(RuntimeException exception, Cache cache,
Object key) {
RedisErrorException(exception, key);
}
@Override
public void handleCacheClearError(RuntimeException exception, Cache cache) {
RedisErrorException(exception, null);
}
};
return cacheErrorHandler;
}
protected void RedisErrorException(Exception exception,Object key){
log.error("redis异常:key=[{}]", key, exception);
}
}
5:缓存配置
public class GoodsRedisConst {
/**
* 全局RedisKey 前缀
*/
public static final String PREFIX = "GD:";
public static final String NAME_TIME_CONFIG_SEPARATOR = "\\(";
public static final String TTL_TIME_SEPARATOR = "\\)";
/**
* 默认过期时间
*/
public static final Long DEFAULT_TIME = 5 * 60L;
public static Random EXPIRE_RANDOM = getInstanceC();
public static Random getInstanceC() {
// 先判断实例是否存在,若不存在再对类对象进行加锁处理
if (EXPIRE_RANDOM == null) {
synchronized (Random.class) {
if (EXPIRE_RANDOM == null) {
EXPIRE_RANDOM = new Random();
}
}
}
return EXPIRE_RANDOM;
}
}
二:注解详解
1. @Cacheable
1.1 使用场景
最常用的注解,将注解方法的返回值缓存。
工作原理是:首先在缓存中查找,如果没有执行方法并缓存结果,然后返回数据。此注解的缓存名必须指定
示例:
@Override
@Cacheable(value = {"idKey(600)s"},keyGenerator = "keyGenerator",condition = "#g.id.equals(1L)")
public GoodsInfo getGoodsInfo(GoodsInfo g) {
GoodsInfo goodsInfo = new GoodsInfo();
goodsInfo.setCategoryId(1L);
goodsInfo.setCategoryName("缓存测试");
goodsInfo.setId(1L);
System.err.println("没有命中缓存");
if (g.getId().equals(goodsInfo.getId())){
return goodsInfo;
}
goodsInfo.setCategoryName("不走缓存");
return goodsInfo;
}
value、cacheNames
缓存的名称,在 spring 配置文件中定义,必须指定至少一个
例如: @Cacheable(value=”mycache”) @Cacheable(value={”cache1”,”cache2”}
扩展后可以添加缓存过期时间
设置的缓存名称(完整配置的例子 redisKey(10)s)
单位(不区分大小写) s:seconds(秒) m:minutes(分钟) h:hours(小时) d:days(天)
key
缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合
例如: @Cacheable(value=”testcache”,key=”#userName”)
condition
缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false,只有为 true 才进行缓存
例如:@Cacheable(value=”testcache”,condition=”#userName.length()>2”)
1.2 常用参数
- value 等价于name 缓存中的命名空间
- cacheNames 缓存中的命名空间 等价于value
- cacheManager 使用哪一个缓存管理器
- key 生成key值,与keyGenerator互斥,支持SpEL表达式,当我们没有指定该属性时,Spring将使用默认生成策略生成key值
- keyGenerator key的生成策略是一个对象,可以使用默认的生成策略,也可以自定义生成策略
- condition 缓存生成条件 支持SpEL表达式
- unless 不生成缓存条件 支持SpEL表达式
1.3 默认生成策略
默认的key生成策略是通过KeyGenerator生成的,其默认策略如下:
-
如果方法没有参数,则使用0作为key。
-
如果只有一个参数的话则使用该参数作为key。
-
如果参数多余一个的话则使用所有参数的hashCode作为key。
-
下面重写了缓存 key 生成策略,也可以自定义缓存生成策略,然后通过keyGenerator = "keyGenerator"指定自己的 key 生成策略
/** * 重写key的生成策略() * @return */ @Bean @ConditionalOnMissingBean(KeyGenerator.class) @Override public KeyGenerator keyGenerator() { return (o, method, objects) -> { StringBuilder stringBuilder = new StringBuilder(); /** * //获取类名 * stringBuilder.append(o.getClass().getSimpleName()); * stringBuilder.append("."); * //获取方法名 * stringBuilder.append(method.getName()); * stringBuilder.append(":"); */ //请求参数数组 for (Object obj : objects) { if (obj != null && obj.toString().contains("=")) { HashMap<String, Object> hashMap = JSON.parseObject(JSON.toJSONString(obj), HashMap.class); hashMap.forEach((k, v) -> { stringBuilder.append(k + ":" + v + ":"); }); }else { stringBuilder.append(obj + ":"); } } StringBuilder redisKey = stringBuilder.deleteCharAt(stringBuilder.length() - 1); log.info("redisKey============{}",redisKey); return redisKey; }; }
2. @CacheEvict
2.1 使用场景
常用注解,将@Cacheable缓存清除
示例:
@CacheEvict(value = "idKey(600)s",beforeInvocation = false,allEntries = false)
public void getGoodsInfoDel(GoodsInfo g) {
}
value
缓存的名称,在 spring 配置文件中定义,必须指定至少一个
例如: @CacheEvict(value=”my cache”)
key
缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合
例如: @CacheEvict(value=”testcache”,key=”#userName”)
condition
缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false,只有为 true 才进行缓存
例如: @CacheEvict(value=”testcache”,condition=”#userName.length()>2”)
allEntries
是否清空所有缓存内容,缺省为 false,如果指定为 true,则方法调用后将立即清空所有缓存
例如: @CachEvict(value=”testcache”,allEntries=true)
beforeInvocation
是否在方法执行前就清空,缺省为 false,如果指定为 true,则在方法还没有执行的时候就清空缓存,缺省情况下,如果方法执行抛出异常,则不会清空缓存
例如: @CachEvict(value=”testcache”,beforeInvocation=true)
2.2 常用参数
- value 等价于name 缓存中的命名空间
- cacheNames 缓存中的命名空间 等价于value
- cacheManager 使用哪一个缓存管理器
- key 生成key值 与keyGenerator互斥,支持SpEL表达式,当我们没有指定该属性时,Spring将使用默认生成策略生成key值
- keyGenerator key的生成策略是一个对象,可以使用默认的生成策略,也可以自定义生成策略
- condition 缓存清除条件 支持SpEL表达式
- allEntries 是否清除所有缓存 默认:false(根据 value 中的值匹配)
- beforeInvocation 方法调用前清除还是之后清除 默认:false (调用后清除)
3. @CachePut
3.1 使用场景
常用注解,用于在update和insert场景,在更新/添加之后,更新缓存值
示例:
@CachePut(value = "idKey(600)s",
key = "'id:'.concat(#goodsInfo.id).concat(':creatorId:').concat(#goodsInfo.creatorId)")
public GoodsInfo getByIdUpdate(GoodsInfo g) {
g.setCategoryId(1L);
g.setCategoryName("修改缓存");
g.setId(1L);
return g;
}
3.1 常用参数
- value 等价于name 缓存中的命名空间
- cacheNames 缓存中的命名空间 等价于value
- cacheManager 使用哪一个缓存管理器
- key 生成key值,与keyGenerator互斥,支持SpEL表达式,当我们没有指定该属性时,Spring将使用默认生成策略生成key值
- keyGenerator key的生成策略是一个对象,可以使用默认的生成策略,也可以自定义生成策略
- condition 缓存生成条件 支持SpEL表达式
- unless 不生成缓存条件 支持SpEL表达式
4. @Caching
4.1 使用场景
用于多种普通注解组合,因为同一个方法只能使用一个相同注解,为了解决这个问题,引入了@caching注解
示例:
@Caching(evict = {
@CacheEvict(value = "queryMasterOrderDetail", key = "'queryMasterOrderDetail~'+ #orderNum", cacheManager = "shortCacheManager"),
@CacheEvict(value = "queryCustomerBuildingAccountByOrderNum", key = "'queryCustomerBuildingAccountByOrderNum~' + #orderNum")
})
public Integer deleteOrderAccount(Long orderNum) {
}
4.2 常用参数
- cacheable 多个@Cacheable组合使用
- put 多个@CachePut组合使用
- evict 多个@CacheEvict组合使用
三: SpEL表达式
1. 基础
名字 | 位置 | 描述 | 示例 |
---|---|---|---|
methodName | root对象 | 当前被调用的方法名 | #root.methodName |
method | root对象 | 当前被调用的方法 | #root.method |
target | root对象 | 当前被调用的目标对象 | #root.target |
targetClass | root对象 | 当前被调用的目标对象类 | #root.targetClass |
args | root对象 | 当前被调用的方法的参数列表 | #root.args |
caches | root对象 | 当前方法调用使用的缓存列表(如@Cacheable(value={“cache1”, “cache2”})),则有两个cache | #root.caches |
参数名称 | 执行上下文 | 当前被调用的方法的参数,如findById(Long id),我们可以通过#id拿到参数 | #id/#user.id |
result | 执行上下文 | 方法执行后的返回值(仅当方法执行之后的判断有效,如‘unless’,'cache evict’的beforeInvocation=false) | #result |
2:调用静态方法
//T(org.springframework.util.ObjectUtils).isEmpty(#orderNum)
@CacheEvict(value = "query", key = "'query:'+ #orderNum",
condition="T(org.springframework.util.ObjectUtils).isEmpty(#orderNum)")
public Integer deleteOrderAccount(Long orderNum) {
...
}
3:正则匹配
@CacheEvict(value = "query", key = "'query:' + #orderNum",condition="#orderNum match '\d{6}'")
public Integer deleteOrderAccount(Long orderNum) {
...
}
四:异常
1:可能出现异常
返回值强制转换的异常
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
默认情况下,redis使用Jackson进行反序列化json,但是json不能告诉Jackson,这个数字是int还是long,所以当数字在小于Integer.MAX_INT时候,Jackson默认将数字序列化成int类型,当int类型数字注入Long型对象则会出现这个错误