將父類的 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 {/*** 不方便使用注解時,調用該方法可以執行異步操作。*/@Asyncpublic void exe(Runnable runner) {runner.run();}/*** TtlExecutors 這個線程池很重要,可以讓子線程繼承父線程的threadLocal數據* @return*/@Beanpublic Executor taskExecutor() {ExecutorService executor = ThreadUtil.newExecutor(10, 200);ExecutorService ttlExecutor = TtlExecutors.getTtlExecutorService(executor);return ttlExecutor;}}