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

}
相关推荐
spencer_tseng1 小时前
Stream not available [SysDictDataMapper.xml]
xml·java
蒸蒸yyyyzwd6 小时前
cpp对象模型学习笔记1.1-2.8
java·笔记·学习
qq_297574676 小时前
【实战教程】SpringBoot 集成阿里云短信服务实现验证码发送
spring boot·后端·阿里云
程序员徐师兄7 小时前
Windows JDK11 下载安装教程,适合新手
java·windows·jdk11 下载安装·jdk11 下载教程
RANCE_atttackkk7 小时前
[Java]实现使用邮箱找回密码的功能
java·开发语言·前端·spring boot·intellij-idea·idea
五岳8 小时前
DTS按业务场景批量迁移阿里云MySQL表实战(下):迁移管理平台设计与实现
java·应用·dts
韩立学长8 小时前
【开题答辩实录分享】以《智能大学宿舍管理系统的设计与实现》为例进行选题答辩实录分享
数据库·spring boot·后端
zhougl9968 小时前
Java 所有关键字及规范分类
java·开发语言
Python 老手8 小时前
Python while 循环 极简核心讲解
java·python·算法
java1234_小锋8 小时前
Java高频面试题:MyISAM索引与InnoDB索引的区别?
java·开发语言