|
|
@@ -0,0 +1,50 @@
|
|
|
+package com.kym.common.aspect;
|
|
|
+
|
|
|
+import com.kym.common.annotation.DynamicCache;
|
|
|
+import com.kym.common.cache.DynamicDataCache;
|
|
|
+import com.kym.common.utils.CommUtil;
|
|
|
+import org.aspectj.lang.ProceedingJoinPoint;
|
|
|
+import org.aspectj.lang.annotation.Around;
|
|
|
+import org.aspectj.lang.annotation.Aspect;
|
|
|
+import org.aspectj.lang.annotation.Pointcut;
|
|
|
+import org.aspectj.lang.reflect.MethodSignature;
|
|
|
+import org.springframework.stereotype.Component;
|
|
|
+
|
|
|
+import java.lang.reflect.Method;
|
|
|
+
|
|
|
+/**
|
|
|
+ * @author skyline
|
|
|
+ * @description 数据缓存切面
|
|
|
+ * @date 2023-11-08 22:27
|
|
|
+ */
|
|
|
+@Component
|
|
|
+@Aspect
|
|
|
+public class DynamicCacheAspect {
|
|
|
+ private DynamicDataCache cache = DynamicDataCache.INSTANCE;
|
|
|
+
|
|
|
+ @Pointcut("@annotation(com.kym.common.annotation.DynamicCache)")
|
|
|
+ public void cachePointCut() {
|
|
|
+ }
|
|
|
+
|
|
|
+ @Around("cachePointCut()")
|
|
|
+ Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
|
|
|
+ MethodSignature signature = (MethodSignature) joinPoint.getSignature();
|
|
|
+ Method method = signature.getMethod();
|
|
|
+ DynamicCache dynamicCache = method.getAnnotation(DynamicCache.class);
|
|
|
+ // 获取方法名
|
|
|
+ var methodName = signature.getName();
|
|
|
+ // 获取注解上的缓存时间
|
|
|
+ var timeout = dynamicCache.timeout();
|
|
|
+ // 获取注解上的缓存key
|
|
|
+ var key = dynamicCache.key();
|
|
|
+ var data = cache.get(CommUtil.isEmptyOrNull(key) ? methodName : key);
|
|
|
+ if (data != null) {
|
|
|
+ return data;
|
|
|
+ }
|
|
|
+ // 缓存无数据则执行原方法,缓存新数据
|
|
|
+ Object result = joinPoint.proceed();
|
|
|
+ // 缓存数据
|
|
|
+ cache.put(CommUtil.isEmptyOrNull(key) ? methodName : key, result, timeout >= 0 ? timeout : 5 * 60 * 1000);
|
|
|
+ return result;
|
|
|
+ }
|
|
|
+}
|