springboot--线程池的 [使用]

tech2024-04-06  53

1.创建配置类

1.1.修改yml文件,配置线程池相关参数
async: corePoolSize: 10 maxPoolSize: 20 queueCapacity: 300 keepAliveSeconds: 60 threadNamePrefix: do-rabbitMq-push
1.2.创建线程池配置类
import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.util.concurrent.Executor; import java.util.concurrent.ThreadPoolExecutor; /** * @program: * @description: 多线程配置类 * @author: Jed * @create: 2020-08-25 17:59 **/ @Configuration @EnableAsync public class AsyncConfiguration { @Value("${async.corePoolSize}") private Integer corePoolSize; @Value("${async.maxPoolSize}") private Integer maxPoolSize; @Value("${async.queueCapacity}") private Integer queueCapacity; @Value("${async.keepAliveSeconds}") private Integer keepAliveSeconds; @Value("${async.threadNamePrefix}") private String threadNamePrefix; @Bean("rabbitMqExecutor") public Executor rabbitMqExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); // 核心线程数:线程池创建时候初始化的线程数 10 executor.setCorePoolSize(corePoolSize); // 最大线程数:线程池最大的线程数,只有在缓冲队列满了之后才会申请超过核心线程数的线程 20 executor.setMaxPoolSize(maxPoolSize); // 缓冲队列:用来缓冲执行任务的队列 500 executor.setQueueCapacity(queueCapacity); // 允许线程的空闲时间60秒:当超过了核心线程之外的线程在空闲时间到达之后会被销毁 60 executor.setKeepAliveSeconds(keepAliveSeconds); // 线程池名的前缀:设置好了之后可以方便我们定位处理任务所在的线程池 do-something- executor.setThreadNamePrefix(threadNamePrefix); // 缓冲队列满了之后的拒绝策略:由调用线程处理(一般是主线程) executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy()); executor.initialize(); return executor; } }
1.3在对应的方法上添加注解@Async(“rabbitMqExecutor”)
@Async("rabbitMqExecutor") public void pushMqProductByIdsAsync(List<String> ids) { if (CollectionUtils.isEmpty(ids)) { return; } //获取数据 List<Product> productList = productMapper.selectBatchIds(ids); for (Product product : productList) { pushMqProduct(product); } }
最新回复(0)