76 lines
2.5 KiB
Java
76 lines
2.5 KiB
Java
package com.zhgd.xmgl.config;
|
||
|
||
import cn.hutool.core.bean.BeanUtil;
|
||
import com.alibaba.fastjson.JSONObject;
|
||
import com.zhgd.xmgl.util.LogMdcUtil;
|
||
import com.zhgd.xmgl.util.ThreadLocalUtil;
|
||
import lombok.extern.slf4j.Slf4j;
|
||
import org.slf4j.MDC;
|
||
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
||
|
||
import java.util.Map;
|
||
import java.util.concurrent.Callable;
|
||
import java.util.concurrent.Future;
|
||
|
||
@Slf4j
|
||
public class MdcThreadPoolTaskExecutor extends ThreadPoolTaskExecutor {
|
||
|
||
/**
|
||
* 接口请求开启的异步线程会调用下述方法
|
||
*/
|
||
@Override
|
||
public void execute(Runnable task) {
|
||
Map<String, String> context = MDC.getCopyOfContextMap(); //复制主线程MDC
|
||
JSONObject tlJo = ThreadLocalUtil.get();
|
||
log.info("MDC异步多线程...");
|
||
JSONObject copyTl = BeanUtil.toBean(tlJo, JSONObject.class);
|
||
super.execute(() -> {
|
||
if (null != context) {
|
||
MDC.setContextMap(context); //主线程MDC赋予子线程
|
||
} else {
|
||
LogMdcUtil.setRequestId(); //主线程没有MDC就自己生成一个
|
||
}
|
||
ThreadLocalUtil.set(copyTl);
|
||
try {
|
||
task.run();
|
||
} finally {
|
||
try {
|
||
LogMdcUtil.clear();
|
||
ThreadLocalUtil.remove();
|
||
} catch (Exception e) {
|
||
log.warn("MDC clear exception:{}", e.getMessage());
|
||
}
|
||
}
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 定时任务会调用下述方法
|
||
*/
|
||
@Override
|
||
public <T> Future<T> submit(Callable<T> task) {
|
||
Map<String, String> context = MDC.getCopyOfContextMap(); //复制主线程MDC
|
||
JSONObject tlJo = ThreadLocalUtil.get();
|
||
log.info("MDC异步多线程...");
|
||
JSONObject copyTl = BeanUtil.toBean(tlJo, JSONObject.class);
|
||
return super.submit(() -> {
|
||
if (null != context) {
|
||
MDC.setContextMap(context); //主线程MDC赋予子线程
|
||
} else {
|
||
LogMdcUtil.setRequestId(); //主线程没有MDC就自己生成一个
|
||
}
|
||
ThreadLocalUtil.set(copyTl);
|
||
try {
|
||
return task.call();
|
||
} finally {
|
||
try {
|
||
LogMdcUtil.clear();
|
||
ThreadLocalUtil.remove();
|
||
} catch (Exception e) {
|
||
log.warn("MDC clear exception:{}", e.getMessage());
|
||
}
|
||
}
|
||
});
|
||
}
|
||
}
|