69 lines
2.4 KiB
Java
Raw Normal View History

2024-05-20 10:01:23 +08:00
package com.zhgd.xmgl.config;
import com.zhgd.xmgl.util.RequestIdUtil;
import lombok.extern.slf4j.Slf4j;
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.slf4j.MDC;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.Map;
@Aspect
@Component
@Slf4j
public class TaskAspect {
@Pointcut("@annotation(org.springframework.scheduling.annotation.Scheduled)")
public void servicePointcut() {
System.out.println("Pointcut: 不会被执行");
}
@Around("servicePointcut()")
public void doAround(ProceedingJoinPoint jointPoint) throws Throwable {
Map<String, String> context = MDC.getCopyOfContextMap(); //复制主线程MDC
// 获取当前访问的class类及类名
Class<?> clazz = jointPoint.getTarget().getClass();
String clazzName = jointPoint.getTarget().getClass().getName();
// 获取访问的方法名
String methodName = jointPoint.getSignature().getName();
try {
if (null == context) {
RequestIdUtil.setRequestId("-t"); //主线程没有MDC就自己生成一个
log.info("task方法开始:{}",methodName);
}
// 获取方法所有参数及其类型
Object[] args = jointPoint.getArgs();
Class[] argClz = ((MethodSignature) jointPoint.getSignature()).getParameterTypes();
// 获取访问的方法对象
Method method = clazz.getDeclaredMethod(methodName, argClz);
// 判断当前访问的方法是否存在指定注解
if (method.isAnnotationPresent(Scheduled.class)) {
Scheduled annotation = method.getAnnotation(Scheduled.class);
// 获取注解标识值与注解描述
// String value = annotation.value();
// String desc = annotation.description();
// 执行目标方法
Object proceed = jointPoint.proceed();
}
} finally {
if (null == context) {
log.info("task方法结束{}",methodName);
2024-05-22 01:33:55 +08:00
RequestIdUtil.clear();
2024-05-20 10:01:23 +08:00
}
}
}
}