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;
    }

}
相关推荐
上进小菜猪1 小时前
面向课堂与自习场景的智能坐姿识别系统——从行为感知到可视化部署的完整工程【YOLOv8】
后端
BestAns2 小时前
一文带你吃透 Java 反射机制
java·后端
wasp5202 小时前
AgentScope Java 核心架构深度解析
java·开发语言·人工智能·架构·agentscope
2501_916766542 小时前
【Springboot】数据层开发-数据源自动管理
java·spring boot·后端
半夏知半秋3 小时前
docker常用指令整理
运维·笔记·后端·学习·docker·容器
程序员码歌3 小时前
短思考第263天,每天复盘10分钟,胜过盲目努力一整年
android·前端·后端
自在极意功。3 小时前
MyBatis 动态 SQL 详解:从基础到进阶实战
java·数据库·mybatis·动态sql
软件管理系统3 小时前
基于Spring Boot的便民维修管理系统
java·spring boot·后端
源代码•宸3 小时前
Leetcode—620. 有趣的电影&&Q3. 有趣的电影【简单】
数据库·后端·mysql·算法·leetcode·职场和发展