作者 朱兆平

redis二级缓存

package com.tianbo.warehouse.annotation.cache.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author mrz
* 缓存清除
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface RedisCacheDelTarget {
/**指定命名规范的key前缀或完整名称
* 类名+方法名+key名称+*
* com.tianbo.warehouse.service.imp.PermissionServiceImp_findAll_findAllMenus
*/
String cacheKey();
//是否清空cacheName的全部数据
boolean allEntries() default true;
}
... ...
... ... @@ -13,10 +13,10 @@ import java.lang.annotation.Target;
@Target({ElementType.METHOD})
public @interface RedisCacheable {
//缓存名称,可以多个
//缓存名称,可以多个。暂时不投入使用
String[] cacheNames() default "";
//缓存key
//缓存key,KEY的名称必须是【#+参数的名称,或者#+{对象名称}】,参考spel表达式
String cacheKey();
//有效期时间(单位:秒),默认8个小时
... ...
package com.tianbo.warehouse.annotation.cache.imp;
import com.tianbo.warehouse.annotation.cache.annotation.RedisCacheDelTarget;
import com.tianbo.warehouse.annotation.cache.annotation.RedisCacheEvict;
import com.tianbo.warehouse.annotation.cache.annotation.RedisCachePut;
import com.tianbo.warehouse.annotation.cache.annotation.RedisCacheable;
import com.tianbo.warehouse.util.IO.JDKSerializeUtil;
import com.tianbo.warehouse.util.redis.DefaultKeyGenerator;
import com.tianbo.warehouse.annotation.cache.util.JDKSerializeUtil;
import com.tianbo.warehouse.annotation.cache.util.redis.DefaultKeyGenerator;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
... ... @@ -41,7 +42,7 @@ public class RedisCacheableAspect {
public Object cached(final ProceedingJoinPoint pjp , RedisCacheable cache) throws Throwable {
try{
//生成缓存KEY
String[] keys = defaultKeyGenerator.generateKey(pjp, cache.cacheNames(), cache.cacheKey());
String[] keys = defaultKeyGenerator.generateKey(pjp, cache.cacheKey());
Object valueData = null;
for(String key : keys){
//获取缓存中的值
... ... @@ -137,4 +138,30 @@ public class RedisCacheableAspect {
}
return pjp.proceed();
}
/**
* @Description: 删除指定KEY命名规范的缓存
* @param:
* @return:
* @throws:
* @author: pengl
* @Date:2017/11/13 17:09
*/
@Around(value = "@annotation(redisCacheDelTarget)")
public Object cacheEvict (final ProceedingJoinPoint pjp , RedisCacheDelTarget redisCacheDelTarget) throws Throwable{
try{
String cacheKey = redisCacheDelTarget.cacheKey();
boolean allEntries = redisCacheDelTarget.allEntries();
if(allEntries){
if(cacheKey!=null){
Long result = redisTemplate.delete(redisTemplate.keys(cacheKey+"*"));
log.info("已删除{}个缓存",result);
}
}
}catch (Exception e){
log.error("批量删除Redis缓存失败,异常信息:" + e.getMessage());
}
return pjp.proceed();
}
}
... ...
package com.tianbo.warehouse.util.IO;
package com.tianbo.warehouse.annotation.cache.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
... ...
package com.tianbo.warehouse.util.redis;
package com.tianbo.warehouse.annotation.cache.util.redis;
import com.alibaba.druid.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
... ... @@ -31,6 +31,7 @@ public class DefaultKeyGenerator {
}
Signature signature = pjp.getSignature();
if(cacheNames == null || cacheNames.length == 0){
cacheNames = new String[]{signature.getDeclaringTypeName() + "." + signature.getName()};
}
... ... @@ -40,18 +41,91 @@ public class DefaultKeyGenerator {
if (!(signature instanceof MethodSignature)) {
throw new IllegalArgumentException("This annotation can only be used for methods...");
}
/**
* 缓存KEY 的命名规范
* 类名+方法名+key名称+参数1名+参数1值+。。。
* (加上key名称是为了防止方法名重复)
* 开始生成缓存key名称
*/
MethodSignature methodSignature = (MethodSignature) signature;
String targetClassName = pjp.getTarget().getClass().getName();
String targetMethodName = methodSignature.getName();
//method参数列表
String[] parameterNames = methodSignature.getParameterNames();
Object[] args = pjp.getArgs();
StringBuffer sb = new StringBuffer();
//evaluationContext存储参数的kEY与Value
for(int i = 0; i < parameterNames.length; i++){
String parameterName = parameterNames[i];
sb.append(parameterName).append("_").append("Value").append("_").append(args[i]);
log.info("=============>>>generateKeys :{}",sb.toString());
evaluationContext.setVariable(parameterName, args[i]);
}
/**
* 缓存key名称生成结束
*/
//通过cachekey的值,从evaluationContext中根据cachekey的值获取其value
for(int j = 0; j < cacheNames.length; j++){
results[j] = "RedisKey_CacheName_" + cacheNames[j] + "_CacheKey_" +
new SpelExpressionParser().parseExpression(cacheKey).getValue(evaluationContext, String.class);//暂时只使用String类型
results[j] = sb.insert(0,cacheNames).toString();
// results[j] = "RedisKey_CacheName_" + cacheNames[j] + "_CacheKey_" +
// new SpelExpressionParser().parseExpression(cacheKey).getValue(evaluationContext, String.class);//暂时只使用String类型
}
log.info("=============>>>generateKeys : " + Arrays.toString(results));
return results;
}
public String[] generateKey(ProceedingJoinPoint pjp,String cacheKey) throws NoSuchMethodException {
if (StringUtils.isEmpty(cacheKey)) {
throw new NullPointerException("CacheKey can not be null...");
}
Signature signature = pjp.getSignature();
EvaluationContext evaluationContext = new StandardEvaluationContext();
if (!(signature instanceof MethodSignature)) {
throw new IllegalArgumentException("This annotation can only be used for methods...");
}
String[] results = new String[1];
/**
* 缓存KEY 的命名规范
* 类名+方法名+key名称+参数1名+参数1值+。。。
* (加上key名称是为了防止方法名重复)
* 开始生成缓存key名称
*/
MethodSignature methodSignature = (MethodSignature) signature;
String targetClassName = pjp.getTarget().getClass().getName();
String targetMethodName = methodSignature.getName();
//method参数列表
String[] parameterNames = methodSignature.getParameterNames();
Object[] args = pjp.getArgs();
StringBuffer sb = new StringBuffer();
sb.append(targetClassName).append("_")
.append(targetMethodName).append("_")
.append(cacheKey).append("_");
//evaluationContext存储参数的kEY与Value
for(int i = 0; i < parameterNames.length; i++){
String parameterName = parameterNames[i];
sb.append("P").append(parameterName).append("_")
.append("V").append(args[i]);
evaluationContext.setVariable(parameterName,args[i]);
}
results[0] = sb.toString();
//通过cachekey的值,从evaluationContext中根据cachekey的值获取其value,
//类名+方法名+key名称+参数1名+参数1值+。。。
// new SpelExpressionParser().parseExpression(cacheKey).getValue(evaluationContext, String.class);//暂时只使用String类型
/**
* 缓存key名称生成结束
* com.tianbo.warehouse.service.imp.PermissionServiceImp_findAll_findAllMenus_PpageNum_V1PpageSize_V500Pname_V
*/
log.info("=============>>>generateKeys : " + Arrays.toString(results));
return results;
}
... ...