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 小时前
【深度长文】万字攻克网络原理:从 HTTP 报文解构到 HTTPS 终极加密逻辑
java·开发语言·网络·python·http·ai·https
想用offer打牌2 小时前
MCP (Model Context Protocol) 技术理解 - 第二篇
后端·aigc·mcp
曹牧4 小时前
Spring Boot:如何测试Java Controller中的POST请求?
java·开发语言
KYGALYX4 小时前
服务异步通信
开发语言·后端·微服务·ruby
掘了4 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
爬山算法4 小时前
Hibernate(90)如何在故障注入测试中使用Hibernate?
java·后端·hibernate
kfyty7254 小时前
集成 spring-ai 2.x 实践中遇到的一些问题及解决方案
java·人工智能·spring-ai
猫头虎5 小时前
如何排查并解决项目启动时报错Error encountered while processing: java.io.IOException: closed 的问题
java·开发语言·jvm·spring boot·python·开源·maven
李少兄5 小时前
在 IntelliJ IDEA 中修改 Git 远程仓库地址
java·git·intellij-idea
Moment5 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端