package com.gs.xky.config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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; /** * 异步任务配置类 * 配置专用线程池处理异步任务,避免阻塞Spring默认线程池 */ @Configuration @EnableAsync public class AsyncConfig { private static final Logger log = LoggerFactory.getLogger(AsyncConfig.class); /** * 配置采购订单同步任务专用线程池 * 使用有限的线程数,避免资源竞争 */ @Bean(name = "purchaseTaskExecutor") public Executor purchaseTaskExecutor() { log.info("创建采购订单同步任务专用线程池"); ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); // 核心线程数设置为1,确保同一时间只有一个采购同步任务在执行 executor.setCorePoolSize(1); // 最大线程数设置为2,允许有限的并发 executor.setMaxPoolSize(2); // 队列容量 executor.setQueueCapacity(5); // 线程名称前缀 executor.setThreadNamePrefix("purchase-task-"); // 拒绝策略:当线程池已满时,调用者线程执行任务 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 等待所有任务结束后再关闭线程池 executor.setWaitForTasksToCompleteOnShutdown(true); // 等待时间(秒) executor.setAwaitTerminationSeconds(60); // 初始化线程池 executor.initialize(); return executor; } /** * 配置通用异步任务线程池 * 用于处理其他轻量级异步任务 */ @Bean(name = "taskExecutor") public Executor taskExecutor() { log.info("创建通用异步任务线程池"); ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); // 核心线程数 executor.setCorePoolSize(5); // 最大线程数 executor.setMaxPoolSize(10); // 队列容量 executor.setQueueCapacity(25); // 线程名称前缀 executor.setThreadNamePrefix("async-task-"); // 拒绝策略:当线程池已满时,调用者线程执行任务 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 初始化线程池 executor.initialize(); return executor; } }