代码示例在最后。
认识一下ThreadPoolTaskExecutor
org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor这是由Sping封装的加强版线程池,其实是Spring使用装饰者模式对ThreadPoolExecutor进一步优化。
它不仅拥有ThreadPoolExecutor所有的核心参数,还有额外的参数可以设置。
我的这个文章有具体的使用案例和ThreadPoolTaskExecutor每个参数的解释:【这样用线程池才优雅-企业级线程池示例】,该文第三节我给出了我目前在使用的ThreadPoolTaskExecutor完整配置,欢迎参考指正。但是文章的最后留了一个尾巴,线程池配置中注释掉了这一行://executor.setTaskDecorator(new ContextCopyingDecorator());
本文将主要介绍ThreadPoolTaskExecutor的setTaskDecorator方法。
解释ThreadPoolTaskExecutor.setTaskDecorator()
先看一下setTaskDecorator方法的官方注释:
Specify a custom TaskDecorator to be applied to any Runnable about to be executed.
Note that such a decorator is not necessarily being applied to the user-supplied Runnable/Callable but rather to the actual execution callback (which may be a wrapper around the user-supplied task).
The primary use case is to set some execution context around the task's invocation, or to provide some monitoring/statistics for task execution.
NOTE: Exception handling in TaskDecorator implementations is limited to plain Runnable execution via execute calls. In case of #submit calls, the exposed Runnable will be a FutureTask which does not propagate any exceptions; you might have to cast it and call Future#get to evaluate exceptions. See the ThreadPoolExecutor#afterExecute javadoc for an example of how to access exceptions in such a Future case.
Since:
4.3
简单翻译一下就是:为线程池的待执行任务(Runnable)指定一个装饰器,主要用途是在任务调用前后设置一些执行上下文,或者为任务执行提供一些监控/统计信息。
实际上就是采用装饰者模式,给工作任务做了一个切面,让我们可以给任务设置一些上下文参数或者监控。
setTaskDecorator的应用场景
1. 解决:InheritableThreadLocal与线程池共用的问题
在文章【解决:InheritableThreadLocal与线程池共用的问题】的最后,我提到ThreadPoolTaskExecutor.setTaskDecorator()可以优雅的解决InheritableThreadLocal与线程池共用的问题。
回顾一下问题详细,由于线程池中的工作线程是可以复用的,所以父线程将任务交给线程池处理的时候并不会调用new Thread(),导致父线程中的 InheritableThreadLocal 变量的值不能被线程池中的工作线程继承(上面提到的文章有详细解释)。为了解决这个问题,我们可以自定义TaskDecorator,在工作线程执行之前,将父线程的InheritableThreadLocal参数赋值给子线程,这样子线程间接继承父线程InheritableThreadLocal。(代码在最后)
2. 传递MDC日志上下文,方便日志链路追踪
MDC(Mapped Diagnostic Context,映射调试上下文)是 log4j 和 logback 提供的一种方便在多线程条件下记录日志的功能,也可以说是一种轻量级的日志跟踪工具。很多的时候,项目会在MDC中设置一个会话唯一的trace_id,用于追踪整个会话的日志链路。
MDC.put("trace_id", UUID.randomUUID().toString());
但是这个trace_id同样也会在线程池的工作线程中丢失。所以我们可以通过自定义TaskDecorator解决这个问题。
3. 传递Http请求上下文
跟上面的情况差不多,不做叙述。
自定义TaskDecorator代码示例
public class ContextCopyingDecorator implements TaskDecorator {
public static final ThreadLocal<String> CONTEXT = new InheritableThreadLocal<>(); // 新建继承式上下文
@Override
public Runnable decorate(Runnable runnable) {
try {
String contextLocal = CONTEXT.get(); // 获取主线程上下文
RequestAttributes context = RequestContextHolder.currentRequestAttributes(); // 获取主线程上下文
Map<String, String> previous = MDC.getCopyOfContextMap(); // 获取主线程上下文
SecurityContext securityContext = SecurityContextHolder.getContext(); // 获取主线程上下文
return () -> {
try {
ContextCopyingDecorator.CONTEXT.set(contextLocal); // 线程池继承主线程上下文
RequestContextHolder.setRequestAttributes(context); // 子线程继承父线程的RequestAttributes
MDC.setContextMap(previous); // 子线程继承父线程的MDC
SecurityContextHolder.setContext(securityContext); // 子线程继承父线程的SecurityContext
runnable.run(); // 执行异步任务
} finally {
// 线程池任务执行结束则清理上下文
ContextCopyingDecorator.CONTEXT.remove(); // 子线程执行结束后清理CONTEXT
RequestContextHolder.resetRequestAttributes(); // 子线程执行结束后清理RequestContextHolder
MDC.clear(); // 子线程执行结束后清理MDC
SecurityContextHolder.clearContext(); // 子线程执行结束后清理SecurityContextHolder
}
};
} catch (IllegalStateException e) {
return runnable;
}
}
}
这个自定义TaskDecorator可以通过ThreadPoolTaskExecutor.setTaskDecorator()方法设置给你的线程池,这时再使用该线程池的时候就可以解决以上提到的三个问题。
//填充装饰器﹣用来设置线程的上下文
executor.setTaskDecorator(new ContextCopyingDecorator());