相关知识点
- ThreadLocal:一种保证一种规避多线程访问出现线程不安全的方法,当我们在创建一个变量后,如果每个线程对其进行访问的时候访问的都是线程自己的变量这样就不会存在线程不安全问题。
- MDC:(Mapped Diagnostic Context,映射调试上下文)是 log4j 和 logback 提供的一种方便在多线程条件下记录日志的功能,基于ThreadLocal实现的一种工具类。
- API
clear() :移除所有MDC
get (String key) :获取当前线程MDC中指定key的值
put(String key, Object o) :往当前线程的MDC中存入指定的键值对
getContext() :获取当前线程MDC的MDC
remove(String key) :删除当前线程MDC中指定的键值对
代码实现
1. 封装TraceId工具类
public class ThreadMDCUtil {
public static final String TRACE_ID = "TRACE_ID";
public static String getTraceId(){
return MDC.get(TRACE_ID);
}
public static String generatorTraceId(){
return UUID.randomUUID().toString();
}
public static void setTraceIdIfAbsent(String traceId){
if(MDC.get(TRACE_ID) == null){
traceId = StringUtils.isEmpty(traceId) ? generatorTraceId() : traceId;
MDC.put(TRACE_ID,traceId);
}
}
/**
* 用于父线程 向 线程池中提交任务时,将MDC中traceid传给子线程
* @param callable
* @param context
* @return
* @param <T>
*/
public static <T> Callable<T> wrap(final Callable<T> callable, final Map<String,String> context){
return () -> {
if(Objects.isNull(context)){
MDC.clear();
}else {
MDC.setContextMap(context);
}
setTraceIdIfAbsent(null);
try {
return callable.call();
} finally {
MDC.clear();
}
};
}
/**
* 用于父线程 向 线程池中提交任务时,将MDC中traceid传给子线程
* @param runnable
* @param context
* @return
*/
public static Runnable wrap(final Runnable runnable,final Map<String,String> context){
return () -> {
if(Objects.isNull(context)){
MDC.clear();
}else {
MDC.setContextMap(context);
}
setTraceIdIfAbsent(null);
try {
runnable.run();
} finally {
MDC.clear();
}
};
}
}
2. 重写线程池
使用ThreadMdcUtil重新进行封装,并在启动类中调用。为了将traceid加入到线程中,并显示在滚动日志中。
MDC底层实现是基于Threadlocal 实现的,如果在主线程中使用了线程池,开启了子线程,主、子线程MDC是相互隔离的,每个线程最终都会执行 Runable,run方法,所以这里只需包装一下Runable,run方法结束之后清理MDC。
import org.slf4j.MDC;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
//线程池 增加 mdc trace 传递
public class TraceThreadPoolTaskExceutor extends ThreadPoolTaskExecutor {
public TraceThreadPoolTaskExceutor() {
super();
}
@Override
public void execute(Runnable tack) {
super.execute(ThreadMDCUtil.wrap(tack, MDC.getCopyOfContextMap()));
}
@Override
public void execute(Runnable task, long startTimeout) {
super.execute(ThreadMDCUtil.wrap(task, MDC.getCopyOfContextMap()), startTimeout);
}
@Override
public Future<?> submit(Runnable task) {
return super.submit(ThreadMDCUtil.wrap(task, MDC.getCopyOfContextMap()));
}
@Override
public <T> Future<T> submit(Callable<T> task) {
return super.submit(ThreadMDCUtil.wrap(task, MDC.getCopyOfContextMap()));
}
}
3. 异步注入线程池
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.boot.autoconfigure.task.TaskExecutionProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
/**
* 注意:要充分考虑不同业务组的异常线程池使用情况,流量较大的一定要使用独立线程池
*/
@Slf4j
@Configuration
@EnableAsync
@EnableScheduling
public class AsyncConfiguration implements AsyncConfigurer {
public static final String SYNC_COMMON_EXECUTOR = "SyncCommonExecutor";
private final TaskExecutionProperties taskExecutionProperties;
public AsyncConfiguration(TaskExecutionProperties taskExecutionProperties) {
this.taskExecutionProperties = taskExecutionProperties;
}
/**
* 未作tracer包装的线程池,如zipkin需要用LazyTraceThreadPoolTaskExecutor包装
*/
@Override
@Bean(name = SYNC_COMMON_EXECUTOR)
public Executor getAsyncExecutor() {
log.debug("Creating Async Task Executor");
ThreadPoolTaskExecutor executor = new TraceThreadPoolTaskExceutor();
executor.setTaskDecorator(new ContentCopyingDecorator());
executor.setCorePoolSize(taskExecutionProperties.getPool().getCoreSize());
executor.setMaxPoolSize(taskExecutionProperties.getPool().getMaxSize());
executor.setQueueCapacity(taskExecutionProperties.getPool().getQueueCapacity());
executor.setThreadNamePrefix(taskExecutionProperties.getThreadNamePrefix());
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new SimpleAsyncUncaughtExceptionHandler();
}
}
4.定义TaskDecorator实例
开发中很多数据如oauth2的认证信息,日志TracerId都是在请求线程中的,如果内部使用多线程处理就存在获取不到认证信息或TraceId的问题。这时候就需要处理子线程与主线程间数据传递的问题。
这个问题需要使用线程的ThreadLocal和TaskDecorator来处理。官方文档中描述意思是TaskDecorator是一个执行回调方法的装饰器,主要应用于传递上下文,或者提供任务的监控/统计信息。
实现方式就是定义一个TaskDecorator,在线程池中设置使用这个TaskDecorator。
注意线程池中有的线程是一直存在一直被复用的,所以线程执行完成后需要在TaskDecorator的finally方法中移除传递的上下文对象,否则就存在内存泄漏的问题。
继承TaskDecorator接口创建ContextCopyingDecorator 实现类,重写decorate方法,设置需要传递的上下文和变量值。注意finally代码块。
import org.springframework.core.task.TaskDecorator;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
public class ContentCopyingDecorator implements TaskDecorator {
@Override
public Runnable decorate(Runnable runnable) {
RequestAttributes context = RequestContextHolder.currentRequestAttributes();
return () -> {
try {
RequestContextHolder.setRequestAttributes(context);
runnable.run();
} finally {
RequestContextHolder.resetRequestAttributes();
}
};
}
}
5. 配置日志输出格式
<pattern>[%X{TRACE_ID}][%d{yyyy-MM-dd HH:mm:ss.SSS} %5p %logger{0}:%L] %msg%n</pattern>
6. 这里使用的切面形式,也可以使用 filter 的形式
import com.example.demo.utils.DateFormatUtil;
import com.example.demo.utils.JsonUtil;
import org.aspectj.lang.JoinPoint;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @Description: 请求日志
*/
@Aspect
@Component
public class WebLogAspect {
private static final Logger log = LoggerFactory.getLogger("accessDataLog");
@Pointcut("execution(public * com.example.demo.controller.*.*(..))")
public void weblog() {
}
@Around("weblog()")
public Object doRound(ProceedingJoinPoint joinPoint) {
StringBuilder msg = new StringBuilder();
Date reqTime = new Date();
try {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String tid = request.getRemoteHost() + ":" + request.getRemotePort() + "-" + UUID.randomUUID().toString();
// 可在此处扩展,从request中获取traceId,串联整个链路
MDC.put(ThreadMDCUtil.TRACE_ID, tid);
msg.append(" remote ip:");
msg.append(request.getRemoteAddr());
msg.append(" request url:");
msg.append(request.getRequestURL().toString());
msg.append(" param:");
msg.append(JsonUtil.toJson(getParams(joinPoint)));
Object result = joinPoint.proceed();
msg.append(" resp:");
msg.append(JsonUtil.toJson(result));
return result;
} catch (Throwable e) {
log.error("request aop error", e);
msg.append(" resp: error:").append(e.getMessage());
throw new RuntimeException(e);
} finally {
msg.append(" reqTime:").append(DateFormatUtil.formatyyyyMMddHHmmssSSS(reqTime));
msg.append(" respTime:").append(DateFormatUtil.formatyyyyMMddHHmmssSSS(new Date()));
msg.append(" cost:").append(System.currentTimeMillis() - reqTime.getTime());
log.info(msg.toString());
MDC.clear();
}
}
private Object getParams(JoinPoint joinPoint) {
return Stream.of(joinPoint.getArgs())
.filter(Objects::nonNull)
.filter(o -> !(o instanceof ServletRequest))
.filter(o -> !(o instanceof ServletResponse))
.map(o -> {
if (o instanceof MultipartFile) {
return ((MultipartFile) o).getOriginalFilename();
}
return o;
})
.collect(Collectors.toList());
}
}
最终呈现效果
参考博客:
https://blog.csdn.net/hansome_hong/article/details/124434864
https://www.cnblogs.com/yin-feng/p/15921001.html
https://blog.csdn.net/qq_29569183/article/details/111311632
https://blog.csdn.net/qq_43602576/article/details/131555515