springboot 配置線程池

1.添加配置類

 @Configuration
    @EnableAsync
    public class ThreadPoolConfig {
    
        @Bean("taskExecutor")
        public TaskExecutor taskExecutor() {
            ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
            // 設置核心線程數
            executor.setCorePoolSize(10);
            // 設置最大線程數
            executor.setMaxPoolSize(20);
            // 設置隊列容量
            executor.setQueueCapacity(200);
            // 設置線程活躍時間(秒)
            executor.setKeepAliveSeconds(60);
            // 設置默認線程名稱
            executor.setThreadNamePrefix("taskExecutor-");
            // 設置拒絕策略
            executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
            // 等待所有任務結束後再關閉線程池
            executor.setWaitForTasksToCompleteOnShutdown(true);
            return executor;
        }
    }

2 在需要異步處理的方法上加上註解

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