使用场景:解耦业务实现和基础组件功能代码
@MyCache(key = "test_'+#code")
public TempObject getTempObject(String code){
}
自定义注解:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyCache {
String key() default "";
}
AOP实现注解拦截+缓存功能
@Aspect
@Component
@Slf4j
public class MyCacheAspect {
@Autowired
private RedisUtil redisUtil;
@Around("@annotation(common.annotations.MyCache)")
public Object doCache(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
Method method = signature.getMethod();
Class<?> returnClass = signature.getReturnType();
MyCache myCache = method.getAnnotation(MyCache.class);
String keyEL = myCache.key();
ExpressionParser parser = new SpelExpressionParser();
Expression expression = parser.parseExpression(keyEL);
EvaluationContext context = new StandardEvaluationContext();
Object[] args = proceedingJoinPoint.getArgs();
String[] parameterNames = new DefaultParameterNameDiscoverer().getParameterNames(method);
for(int i=0;i<parameterNames.length;i++){
context.setVariable(parameterNames[i],args[i]);
}
String key = expression.getValue(context).toString();
log.info("自定义注解生成key:[{}]",key);
String cacheValue = redisUtil.get(key);
if(cacheValue!=null){
log.info("获取缓存数据 key:[{}]",key);
return JSON.parseObject(cacheValue,returnClass);
}
Object object = proceedingJoinPoint.proceed();
redisUtil.set(key,JSON.toJSONString(object));
return object;
}
}