将父类的 threadLocal 的数据 在线程池时,可以转给子线程使用。
@Async 的使用。
第一步在启动服务加上 @EnableAsync 注解。
@EnableAsync
public class NetCoreApplication {
... ...
}
第二步:导入阿里 线程工具类
<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;
@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;
}
}