|
@@ -2,12 +2,15 @@ package com.smppw.modaq.infrastructure.config;
|
|
|
|
|
|
import org.slf4j.Logger;
|
|
|
import org.slf4j.LoggerFactory;
|
|
|
+import org.slf4j.MDC;
|
|
|
import org.springframework.context.annotation.Bean;
|
|
|
import org.springframework.context.annotation.Configuration;
|
|
|
+import org.springframework.core.task.TaskDecorator;
|
|
|
import org.springframework.scheduling.annotation.EnableAsync;
|
|
|
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
|
|
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
|
|
|
|
|
|
+import java.util.Map;
|
|
|
import java.util.concurrent.ThreadPoolExecutor;
|
|
|
|
|
|
@Configuration
|
|
@@ -25,6 +28,7 @@ public class ThreadPoolConfig {
|
|
|
taskExecutor.setThreadNamePrefix("asyncExecutor--");
|
|
|
taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
|
|
|
taskExecutor.setAwaitTerminationSeconds(60);
|
|
|
+ taskExecutor.setTaskDecorator(new MdcTaskDecorator());
|
|
|
|
|
|
// 修改拒绝策略为使用当前线程执行
|
|
|
taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
|
|
@@ -43,6 +47,7 @@ public class ThreadPoolConfig {
|
|
|
scheduler.setAwaitTerminationSeconds(60); // 关闭时等待任务完成的时间
|
|
|
scheduler.setWaitForTasksToCompleteOnShutdown(true); // 关闭时等待任务完成
|
|
|
scheduler.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 拒绝策略
|
|
|
+ scheduler.setTaskDecorator(new MdcTaskDecorator());
|
|
|
|
|
|
// 可选配置
|
|
|
scheduler.setErrorHandler(t -> {
|
|
@@ -55,4 +60,19 @@ public class ThreadPoolConfig {
|
|
|
|
|
|
return scheduler;
|
|
|
}
|
|
|
+
|
|
|
+ static class MdcTaskDecorator implements TaskDecorator {
|
|
|
+ @Override
|
|
|
+ public Runnable decorate(Runnable runnable) {
|
|
|
+ Map<String, String> contextMap = MDC.getCopyOfContextMap();
|
|
|
+ return () -> {
|
|
|
+ try {
|
|
|
+ MDC.setContextMap(contextMap);
|
|
|
+ runnable.run();
|
|
|
+ } finally {
|
|
|
+ MDC.clear();
|
|
|
+ }
|
|
|
+ };
|
|
|
+ }
|
|
|
+ }
|
|
|
}
|