public class MDCThreadPoolTaskExecutor extends ThreadPoolTaskExecutor {
/**
* 带logId的线程执行方法
* @param task
*/
@Override
public void execute(Runnable task) {
ThreadPoolExecutor executor = this.getThreadPoolExecutor();
try {
executor.execute(wrapTask(task, MDC.getCopyOfContextMap()));
} catch (RejectedExecutionException var4) {
throw new TaskRejectedException("Executor [" + executor + "] did not accept task: " + task, var4);
}
}
/**
* 带logId的线程执行方法
* @param task
*/
@Override
public Future<?> submit(Runnable task) {
ThreadPoolExecutor executor = this.getThreadPoolExecutor();
try {
return executor.submit(wrapTask(task, MDC.getCopyOfContextMap()));
} catch (RejectedExecutionException var4) {
throw new TaskRejectedException("Executor [" + executor + "] did not accept task: " + task, var4);
}
}
/**
* 带logId的线程执行方法
* @param task
*/
@Override
public <T> Future<T> submit(Callable<T> task) {
ThreadPoolExecutor executor = this.getThreadPoolExecutor();
try {
return executor.submit(wrapTask(task, MDC.getCopyOfContextMap()));
} catch (RejectedExecutionException var4) {
throw new TaskRejectedException("Executor [" + executor + "] did not accept task: " + task, var4);
}
}
private <T> Callable<T> wrapTask(Callable<T> task, Map<String, String> context) {
return new Callable<T>() {
@Override
public T call() throws Exception {
Map<String, String> previous = MDC.getCopyOfContextMap();
if (previous == null){
MDC.clear();
} else {
MDC.setContextMap(context);
}
try {
return task.call();
} finally {
if (previous == null) {
MDC.clear();
} else {
MDC.setContextMap(previous);
}
}
}
};
}
private Runnable wrapTask(Runnable task, Map<String, String> context){
return new Runnable() {
@Override
public void run() {
Map<String, String> previous = MDC.getCopyOfContextMap();
if (previous == null){
MDC.clear();
} else {
MDC.setContextMap(context);
}
try {
task.run();
} finally {
if (previous == null) {
MDC.clear();
} else {
MDC.setContextMap(previous);
}
}
}
};
}
}
在开启子线程时,将ThreadLocal变量手动传递进去。
|