1.使用TaskDecorator(https://blog.csdn.net/chimo1831/article/details/100604697?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task)
/**
* @author
* @version 1.0
* @date 2020/3/1 10:12
*/
public class MdcTaskDecorator implements TaskDecorator {
/**
* 使异步线程池获得主线程的上下文
* @param runnable
* @return
*/
@Override
public Runnable decorate(Runnable runnable) {
Map<String,String> map = MDC.getCopyOfContextMap();
return () -> {
try{
MDC.setContextMap(map);
runnable.run();
} finally {
MDC.clear();
}
};
}
}
@Configuration
public class AsyncConfig extends AsyncConfigurerSupport {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
threadPoolTaskExecutor.setCorePoolSize(16);
threadPoolTaskExecutor.setMaxPoolSize(48);
threadPoolTaskExecutor.setQueueCapacity(16);
threadPoolTaskExecutor.setThreadNamePrefix("Async-");
threadPoolTaskExecutor.setTaskDecorator(new MdcTaskDecorator());
threadPoolTaskExecutor.initialize();
return threadPoolTaskExecutor;
}
}
2.或者重写线程池
https://blog.csdn.net/weixin_34121282/article/details/92388157
3.
https://blog.csdn.net/linfujian1999/article/details/88309877
https://www.jianshu.com/p/4093add7f2cd
https://blog.csdn.net/chuxiong5717/article/details/100827949