CacheAspect.java 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package com.backendsys.modules.common.config.cache;
  2. import org.aspectj.lang.ProceedingJoinPoint;
  3. import org.aspectj.lang.annotation.Around;
  4. import org.aspectj.lang.annotation.Aspect;
  5. import org.aspectj.lang.reflect.MethodSignature;
  6. import org.springframework.cache.annotation.Cacheable;
  7. import org.springframework.stereotype.Component;
  8. import java.lang.reflect.Method;
  9. @Aspect
  10. @Component
  11. public class CacheAspect {
  12. @Around("@annotation(org.springframework.cache.annotation.Cacheable)")
  13. public Object logCacheableMethod(ProceedingJoinPoint joinPoint) throws Throwable {
  14. MethodSignature signature = (MethodSignature) joinPoint.getSignature();
  15. Method method = signature.getMethod();
  16. // 获取 @Cacheable 注解
  17. Cacheable cacheable = method.getAnnotation(Cacheable.class);
  18. String cacheName = cacheable.value()[0]; // 获取缓存名称
  19. String key = cacheable.key(); // 获取缓存键
  20. // 获取方法参数
  21. Object[] args = joinPoint.getArgs();
  22. String keyExpression = key;
  23. if (keyExpression.contains("#")) {
  24. // 替换表达式中的参数占位符
  25. for (int i = 0; i < args.length; i++) {
  26. keyExpression = keyExpression.replace("#" + signature.getParameterNames()[i], args[i].toString());
  27. }
  28. }
  29. // 执行方法
  30. Object result = joinPoint.proceed();
  31. // 输出日志
  32. System.out.println("记录缓存 (" + cacheName + "): { key: " + keyExpression + ", value: " + result + " }");
  33. return result;
  34. }
  35. }