SpringBoot線程池如何配置?廢話不多說,只需要三個步驟:
1、在項目主類中添加@EnableAsync註解
@SpringBootApplication
@EnableAsync
public class MySpringBootApplication {
private static Logger logger = LoggerFactory.getLogger(MySpringBootApplication.class);
public static void main(String[] args) {
SpringApplication.run(MySpringBootApplication.class, args);
logger.info("My Spring Boot Application Started");
}
}
2、配置線程池
創建一個配置類ExecutorConfig,用來定義如何創建一個ThreadPoolTaskExecutor,要使用@Configuration和@EnableAsync這兩個註解,表示這是個配置類,並且是線程池的配置類,在方法上添加@Bean註解,表示這是我們自己創建的類。如下所示:
@Configuration
@EnableAsync
public class ExecutorConfig {
private static final Logger logger = LoggerFactory.getLogger(ExecutorConfig.class);
@Bean
public Executor asyncServiceExecutor() {
logger.info("start asyncServiceExecutor");
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//配置核心線程數
executor.setCorePoolSize(5);
//配置最大線程數
executor.setMaxPoolSize(5);
//配置隊列大小
executor.setQueueCapacity(99999);
//配置線程池中的線程的名稱前綴
executor.setThreadNamePrefix("async-service-");
// rejection-policy:當pool已經達到max size的時候,如何處理新任務
// CALLER_RUNS:不在新線程中執行任務,而是有調用者所在的線程來執行
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//執行初始化
executor.initialize();
return executor;
}
}
3、方法異步化
在executeAsync方法上增加註解@Async(“asyncServiceExecutor”),asyncServiceExecutor是前面ExecutorConfig.java中的方法名,表明executeAsync方法進入的線程池是asyncServiceExecutor方法創建的,如下:
@Component
public class AsyncTask {
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
@Async("asyncServiceExecutor")
public void executeAsync() {
logger.info("start executeAsync");
try{
Thread.sleep(1000);
}catch(Exception e){
e.printStackTrace();
}
logger.info("end executeAsync");
}
}
如果僅僅是使用的話,按照我這篇文章操作即可。如果想了解的更深的話,非常推薦看下面這篇文章。