注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyRedisCache {
String keyPrefix();
String matchValue();
}
AOP
@Aspect
@Component
public class MyRedisCacheAspect {
@Resource
private RedisTemplate redisTemplate;
@Pointcut("@annotation(com.deloitte.services.duty.config.MyRedisCache)")
public void cachePointCut() {
}
@Around("cachePointCut()")
public Object doCache(ProceedingJoinPoint joinPoint) {
Object result = null;
try {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
MyRedisCache myRedisCache = method.getAnnotation(MyRedisCache.class);
String keyPrefix = myRedisCache.keyPrefix();
String matchValueSpringEL = myRedisCache.matchValue();
ExpressionParser parser = new SpelExpressionParser();
Expression expression = parser.parseExpression(matchValueSpringEL);
EvaluationContext context = new StandardEvaluationContext();
Object[] args = joinPoint.getArgs();
DefaultParameterNameDiscoverer discoverer = new DefaultParameterNameDiscoverer();
String[] parameterNames = discoverer.getParameterNames(method);
for (int i = 0; i < args.length; i++) {
System.out.println("获取方法里参数名和值:" + parameterNames[i] + "\t" + args[i]);
context.setVariable(parameterNames[i], args[i].toString());
}
String key = keyPrefix + ":" + expression.getValue(context).toString();
System.out.println("拼接的redis的key为:" + key);
result = redisTemplate.opsForValue().get(key);
if (result != null) {
return result;
}
result = joinPoint.proceed();
if (result != null) {
redisTemplate.opsForValue().set(key, result);
}
} catch (Throwable e) {
e.printStackTrace();
}
return result;
}
}