|
| 1 | +package me.zhengjie.config.thread; |
| 2 | + |
| 3 | +import org.springframework.context.annotation.Bean; |
| 4 | +import org.springframework.context.annotation.Configuration; |
| 5 | +import org.springframework.context.annotation.Primary; |
| 6 | +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; |
| 7 | +import java.util.concurrent.Executor; |
| 8 | +import java.util.concurrent.ThreadPoolExecutor; |
| 9 | + |
| 10 | +/** |
| 11 | + * 创建自定义的线程池 |
| 12 | + * @author Zheng Jie |
| 13 | + * @description |
| 14 | + * @date 2023-06-08 |
| 15 | + **/ |
| 16 | +@Configuration |
| 17 | +public class CustomExecutorConfig { |
| 18 | + |
| 19 | + /** |
| 20 | + * 自定义线程池,用法 @Async |
| 21 | + * @return Executor |
| 22 | + */ |
| 23 | + @Bean |
| 24 | + @Primary |
| 25 | + public Executor elAsync() { |
| 26 | + ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); |
| 27 | + executor.setCorePoolSize(AsyncTaskProperties.corePoolSize); |
| 28 | + executor.setMaxPoolSize(AsyncTaskProperties.maxPoolSize); |
| 29 | + executor.setQueueCapacity(AsyncTaskProperties.queueCapacity); |
| 30 | + executor.setThreadNamePrefix("el-async-"); |
| 31 | + executor.setKeepAliveSeconds(AsyncTaskProperties.keepAliveSeconds); |
| 32 | + executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); |
| 33 | + executor.initialize(); |
| 34 | + return executor; |
| 35 | + } |
| 36 | + |
| 37 | + /** |
| 38 | + * 自定义线程池,用法 @Async("otherAsync") |
| 39 | + * @return Executor |
| 40 | + */ |
| 41 | + @Bean |
| 42 | + public Executor otherAsync() { |
| 43 | + ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); |
| 44 | + executor.setCorePoolSize(15); |
| 45 | + executor.setQueueCapacity(50); |
| 46 | + executor.setKeepAliveSeconds(AsyncTaskProperties.keepAliveSeconds); |
| 47 | + executor.setThreadNamePrefix("el-task-"); |
| 48 | + executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); |
| 49 | + executor.initialize(); |
| 50 | + return executor; |
| 51 | + } |
| 52 | +} |
0 commit comments