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

}
相关推荐
代码or搬砖1 天前
MyBatisPlus讲解(二)
java·mybatis
Cosolar1 天前
银河麒麟 / aarch64 系统:Docker + Docker Compose 完整安装教程
后端·程序员·架构
星释1 天前
Rust 练习册 100:音乐音阶生成器
开发语言·后端·rust
kaliarch1 天前
2025年IaC生态全景与实践指南:从工具选型到多云治理
后端·云计算·自动化运维
lcu1111 天前
Java 学习42:抽象
java
Mr.朱鹏1 天前
RocketMQ安装与部署指南
java·数据库·spring·oracle·maven·rocketmq·seata
雨中飘荡的记忆1 天前
Spring表达式详解:SpEL从入门到实战
java·spring
Coder-coco1 天前
个人健康管理|基于springboot+vue+个人健康管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·mysql·论文
b***65321 天前
springboot整合mybatis-plus(保姆教学) 及搭建项目
spring boot·后端·mybatis
5***E6851 天前
Spring Boot与MyBatis
spring boot·后端·mybatis