spring boot 异步线程@Async 传递 threadLocal数据

将父类的 threadLocal 的数据 在线程池时,可以转给子线程使用。

@Async 的使用。

第一步在启动服务加上 @EnableAsync 注解。

bash 复制代码
@EnableAsync
public class NetCoreApplication {
	... ...
}

第二步:导入阿里 线程工具类

bash 复制代码
       <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>transmittable-thread-local</artifactId>
            <version>2.14.5</version>
        </dependency>

第三步,增加 线程池。提供给 @Async 用。

ExecutorService executor = ThreadUtil.newExecutor(10, 200);

ExecutorService ttlExecutor = TtlExecutors.getTtlExecutorService(executor);

return ttlExecutor;

bash 复制代码
@Component
public class MyThreadPool {

	 /**
     * 不方便使用注解时,调用该方法可以执行异步操作。
     */
    @Async
    public void exe(Runnable runner) {
        runner.run();
    }

    /**
     * TtlExecutors 这个线程池很重要,可以让子线程继承父线程的threadLocal数据
     * @return
     */
    @Bean
    public Executor taskExecutor() {
        ExecutorService executor = ThreadUtil.newExecutor(10, 200);
        ExecutorService ttlExecutor = TtlExecutors.getTtlExecutorService(executor);
        return ttlExecutor;
    }

}
相关推荐
952361 小时前
Spring-cloud配置中心
java·spring·spring cloud·微服务
ydd1001001 小时前
寻找两个正序数组的中位数 Java 题解,二分分割详解
java·开发语言
65岁退休Coder1 小时前
LangChain v1.3.4 笔记 - 07 补充:链式调用 LCEL
后端·python·langchain
卷无止境1 小时前
FastAPI 部署在 Nginx 后面到底该怎么配
后端·python
码流怪侠1 小时前
用 WiFi 信号数人头:howmanypeoplearearound 项目深度解析
后端·开源·github
心运软件2 小时前
SpringBoot+ Vue校园社团管理平台的完整架构设计
vue.js·后端
真上帝的左手2 小时前
10. 软件设计&架构-Spring Security 7 整合CAS SSO 单点登录
java·spring·架构·sso
Jodie同志2 小时前
第16~23天:持久化、HITL、流式、MCP与安全
前端·后端·agent
Jodie同志2 小时前
第1~15天:原生Agent、RAG与LangGraph基础(完整代码实操)
前端·后端·agent
Zane19943 小时前
单例线程安全、生产者消费者、死锁:并发面试三连问串讲
java·后端