spring boot的線程池配置

spring boot的線程池配置

/**
 * 線程池配置
 *
 */
@EnableAsync 
@Configuration
public class AsyncConfig implements AsyncConfigurer {
	
	//初始化@Async需要的線程池
    @Override
    public Executor getAsyncExecutor() {
    	/**滿足aop的前提下,用@Async註解來做異步執行**/
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5); //核心線程數
        executor.setMaxPoolSize(10);  //最大線程數
        executor.setQueueCapacity(100); //隊列大小
        executor.setKeepAliveSeconds(300); //線程最大空閒時間
        executor.setThreadNamePrefix("async-executor-"); //指定用於新創建的線程名稱的前綴。
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); //拒絕策略(一共四種)
        executor.initialize();
        return executor;
    }

    // 異常處理器
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new SimpleAsyncUncaughtExceptionHandler();
    }
    
    /**
     * 普通線程池
     * @return
     */
    @Bean("normalTheadPool")
    public Executor getTheadPool() {
    	ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5); //核心線程數
        executor.setMaxPoolSize(10);  //最大線程數
        executor.setQueueCapacity(50); //隊列大小
        executor.setKeepAliveSeconds(300); //線程最大空閒時間
        executor.setThreadNamePrefix("normal-thead-pool-"); //指定用於新創建的線程名稱的前綴。
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); //拒絕策略
        executor.initialize();
        return executor;
    }
}

//使用方式
@Async
@Override
public void judgeEnd() {
	startJudge();
}
private void startJudge() {
	system.out.println("異步判斷")
}

通過統一線程池的配置,利用注入的方式來使用線程池對象。需要注意的是使用@Async註解,必須得滿足spring的aop機制。

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