- 開啓異步調用支持
@EnableAsync 啓動類使用註解開啓異步調用
2. 添加異步方法
@Async
public void sendSms(){
System.out.println("@Async");
}
3.配置線程池
@Configuration
@EnableAsync
public class ExecutorConfig {
@Bean
public Executor asyncServiceExecutor() {
LoggerUtil.logger().info("start asyncServiceExecutor");
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//配置核心線程數
executor.setCorePoolSize(5);
//配置最大線程數
executor.setMaxPoolSize(5);
//配置隊列大小
executor.setQueueCapacity(1000);
//配置線程池中的線程的名稱前綴
executor.setThreadNamePrefix("async-service-");
// rejection-policy:當pool已經達到max size的時候,如何處理新任務
// CALLER_RUNS:不在新線程中執行任務,而是有調用者所在的線程來執行
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//執行初始化
executor.initialize();
return executor;
}
}
4.使用註解添加到線程池
@Async("asyncServiceExecutor")
public void sendSms(){
System.out.println("@Async");
}
注意事項:1.在@SpringBootApplication啓動類 添加註解@EnableAsync
2.異步方法使用註解@Async ,返回值爲void或者Future
3.切記一點 ,異步方法和調用方法一定要* 寫在不同的類中 *,如果寫在一個類中, 是沒有效果的