執行緒池 @Async 註解的配置
阿新 • • 發佈:2018-11-02
寫一個Executor配置類:
/** * Description: 自定義執行緒池配置類,核心10個, 最大100個 * User: zhouzhou * Date: 2018-10-24 * Time: 16:20 */ @Configuration @EnableAsync @ConfigurationProperties(prefix = "spring.task.pool") public class ExecutorConfig { /** Set the ThreadPoolExecutor's core pool size. */ private int corePoolSize ; /** Set the ThreadPoolExecutor's maximum pool size. */ private int maxPoolSize ; /** Set the capacity for the ThreadPoolExecutor's BlockingQueue. */ private int queueCapacity; @Bean public Executor mySimpleAsync() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(corePoolSize); executor.setMaxPoolSize(maxPoolSize); executor.setQueueCapacity(queueCapacity); executor.setThreadNamePrefix("ZhouZhouExecutor-"); executor.initialize(); return executor; } @Bean public Executor excelAsync() { // excel的時候用 ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(corePoolSize); executor.setMaxPoolSize(maxPoolSize); executor.setQueueCapacity(queueCapacity); executor.setThreadNamePrefix("ExcelExecutor-"); // rejection-policy:當pool已經達到max size的時候,如何處理新任務 // CALLER_RUNS:不在新執行緒中執行任務,而是有呼叫者所在的執行緒來執行 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); executor.initialize(); return executor; } public int getCorePoolSize() { return corePoolSize; } public void setCorePoolSize(int corePoolSize) { this.corePoolSize = corePoolSize; } public int getMaxPoolSize() { return maxPoolSize; } public void setMaxPoolSize(int maxPoolSize) { this.maxPoolSize = maxPoolSize; } public int getQueueCapacity() { return queueCapacity; } public void setQueueCapacity(int queueCapacity) { this.queueCapacity = queueCapacity; } }
然後再配置yml檔案
# excel解析多執行緒
spring.task.pool:
corePoolSize: 10
maxPoolSize: 100
queueCapacity: 10
最後呼叫的時候,是註解@Async後面加上你的配置的executor的bean的名稱
@Async("excelAsync") public Future<TccResult<ErrorCardOModel>> insertBankCard(BankCardIModel card) { TccResult<ErrorCardOModel> result = new TccResult<>(); .............邏輯 }