85 lines
3.0 KiB
Java
85 lines
3.0 KiB
Java
package com.zhgd.xmgl.config;
|
||
|
||
import com.zhgd.xmgl.constant.Cts;
|
||
import com.zhgd.xmgl.util.LogMdcUtil;
|
||
import com.zhgd.xmgl.util.ThreadLocalUtil;
|
||
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.beans.factory.annotation.Value;
|
||
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 {
|
||
public static Integer onlyPrintInterface;
|
||
|
||
@Value("${onlyPrintInterface:0}")
|
||
public void setOnlyPrintInterface(Integer onlyPrintInterface) {
|
||
TaskAspect.onlyPrintInterface = onlyPrintInterface;
|
||
}
|
||
|
||
@Pointcut("@annotation(org.springframework.scheduling.annotation.Scheduled)")
|
||
public void servicePointcut() {
|
||
}
|
||
|
||
@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) {
|
||
LogMdcUtil.setRequestId("-t"); //主线程没有MDC就自己生成一个
|
||
ThreadLocalUtil.addInKey(Cts.TL_IS_FROM_TASK, true);
|
||
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();
|
||
}
|
||
} catch (Exception e) {
|
||
if (LogMdcUtil.isPrint()) {
|
||
throw e;
|
||
} else {
|
||
log.error("", e);
|
||
}
|
||
} finally {
|
||
if (null == context) {
|
||
log.info("task方法结束:{}", methodName);
|
||
LogMdcUtil.clear();
|
||
ThreadLocalUtil.remove();
|
||
}
|
||
}
|
||
}
|
||
|
||
}
|