SpringBoot 的異步、多線程配置
yml 配置
配置類進行配置
項目里有一些業(yè)務(wù)場景比較獨立琴许,需要異步進行操作,比如發(fā)郵件溉躲、發(fā)短信榜田、不需要實時結(jié)果的復(fù)雜計算益兄,與主線程無關(guān)〖可以使這些方法異步進行净捅,不影響主程序。
SpringBoot 使用@EnableSync 開啟多線程辩块,也可以通過yml文件進行配置蛔六。
yml 配置
可以在Yml 文件里進行配置
1spring:
2 task:
3? execution:
4? ? ? ? ? pool.core-size: 10 # 核心線程數(shù),默認為8
5? ? ? ? ? queue-capacity: 10 # 隊列容量废亭,默認為無限大
6? ? ? ? ? max-size: 10 # 最大線程數(shù)国章,默認為無限大
然后在啟動類上加上注解@EnableAsync,使用的方法上加上@Async
配置類進行配置
也可以通過異步配置豆村,重寫AsyncConfigurer里的getAsyncExecutor()方法液兽,配置文件上加上注解@EnableAsync
1 /**
2 * 異步 多線程配置
3 */
4 @Configuration
5 @EnableAsync
6 public class AsyncConfiguration implements AsyncConfigurer {
8? ?核心線程數(shù)量
9? ?@Value("${my-thread-pool.core-pool-size:10}")
10? ? private Integer corePoolSize;
11? ?最大線程數(shù)量
12? ? @Value("${my-thread-pool.max-pool-size:100}")
13? ? private Integer maxPoolSize;
14? ? 最大線程池緩存隊列數(shù)量
15? ? @Value("${my-thread-pool.queue-capacity:100}")
16? ? private Integer queueCapacity;
17? ? @Override
18? ? public Executor getAsyncExecutor() {
19? ? ? ? ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
20? ? ? ? executor.setCorePoolSize(corePoolSize);
21? ? ? ? executor.setMaxPoolSize(maxPoolSize);
22? ? ? ? executor.setQueueCapacity(queueCapacity);
23? ? ? ? executor.setThreadNamePrefix("zyw-ExecutorThread-");
24? ? ? ? executor.initialize();
25? ? ? ? return executor;
26? ? }
27? ? @Override
28? ? public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
29? ? ? ? return new SimpleAsyncUncaughtExceptionHandler();
30? ? }
31}