详解优雅版线程池ThreadPoolTaskExecutor和ThreadPoolTaskExecutor的装饰器

代码示例在最后。

认识一下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());
  • 15
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
闭包是一个函数对象,它引用了一些在其定义时外部环境的变量。在Python中,闭包常常用来创建装饰器装饰器其实就是一个闭包,它接受一个函数作为参数,并返回一个替代函数。闭包允许我们在不修改原始函数的情况下,添加一些额外的功能或逻辑。 一个典型的装饰器的例子可以是这样的:在一个函数外面定义一个装饰器函数,然后通过在要装饰的函数之前添加@装饰器名称的语法糖,来应用装饰器。 闭包和装饰器的实现机制是类似的,都是通过嵌套函数的方式来实现的。在闭包中,内部函数引用了外部函数的变量。而在装饰器中,装饰器函数接受一个函数作为参数,并返回一个内部函数,内部函数可以访问外部函数的变量。 在闭包和装饰器的实现过程中,都需要注意作用域的规则。在闭包中,内部函数可以访问外部函数的局部变量,而在装饰器中,装饰器函数可以访问被装饰函数的变量。 闭包和装饰器提供了一种灵活的方式来扩展函数的功能,使得我们可以在不修改原始函数的情况下,添加一些额外的逻辑。它们是Python中非常强大而且常用的特性。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [python中的闭包和装饰器解释](https://blog.csdn.net/qq_39567748/article/details/99596644)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *3* [python高级之装饰器](https://blog.csdn.net/qq_35396496/article/details/109147229)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

怪力乌龟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值