SpringBoot 線程池配置 實現AsyncConfigurer接口

線程是開發中常用到的,但是如果沒有定義線程池,程序不斷的創建,銷燬線程,需要消耗很多時間,所以我們定義線程池可以減小這部分時間,我來實現AsyncConfigurer來配置線程池,先看看這個接口有什麼方法

public interface AsyncConfigurer {

	Executor getAsyncExecutor();
	
	AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler();

}

Executor : 處理異步方法調用時要使用的實例,

AsyncUncaughtExceptionHandler :在使用void返回類型的異步方法執行期間拋出異常時要使用的實例。

實現接口代碼如下:

@Configuration
@EnableAsync
@EnableScheduling
public class AsyncConfiguration implements AsyncConfigurer {
   
    private final Logger log = LoggerFactory.getLogger(AsyncConfiguration.class);

    @Override
    @Bean(name = "taskExecutor")
    public Executor getAsyncExecutor() {
        log.debug("Creating Async Task Executor");
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10); //核心線程數
        executor.setMaxPoolSize(20);  //最大線程數
        executor.setQueueCapacity(1000); //隊列大小
        executor.setKeepAliveSeconds(300); //線程最大空閒時間 
        executor.setThreadNamePrefix("ics-Executor-"); ////指定用於新創建的線程名稱的前綴。
        executor.setRejectedExecutionHandler(
		new ThreadPoolExecutor.CallerRunsPolicy()); // 拒絕策略
        return new ExceptionHandlingAsyncTaskExecutor(executor);
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new SimpleAsyncUncaughtExceptionHandler();
    }

}

其中我們主要注意的就是拒絕策略方法:setRejectedExecutionHandler(),拒絕策略常用有有這四種

ThreadPoolExecutor.AbortPolicy 丟棄任務並拋出RejectedExecutionException異常(默認)。
ThreadPoolExecutor.DiscardPolic 丟棄任務,但是不拋出異常。
ThreadPoolExecutor.DiscardOldestPolicy 丟棄隊列最前面的任務,然後重新嘗試執行任務
ThreadPoolExecutor.CallerRunsPolic 由調用線程處理該任務

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章