package com.glxp.api.config; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.util.concurrent.ThreadPoolExecutor; /** * 配置线程池 */ @EnableAsync @Configuration @EnableConfigurationProperties(ThreadPoolConfigProperties.class) public class TaskPoolConfig { // @Bean(name = "taskExecutor") // @Primary // public ThreadPoolTaskExecutor taskExecutor() { // // 获取当前主机的cpu核心数 // int threadCount = Runtime.getRuntime().availableProcessors(); // ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); // //核心池的大小 // taskExecutor.setCorePoolSize(threadCount); // //线程池最大线程数 // taskExecutor.setMaxPoolSize(threadCount * 2); // //队列最大长度 // taskExecutor.setQueueCapacity(200); // //线程空闲时间 // taskExecutor.setKeepAliveSeconds(60); // //配置线程前缀 // taskExecutor.setThreadNamePrefix("custom_executor"); // //配置拒绝策略 // taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // //执行初始化 // taskExecutor.initialize(); // return taskExecutor; // } @Bean(name = "taskExecutor") @Primary public ThreadPoolTaskExecutor taskExecutor(ThreadPoolConfigProperties properties) { // 动态获取CPU核心数 final int cpuCores = Runtime.getRuntime().availableProcessors(); ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); // 核心线程数(配置优先,默认CPU核心数) taskExecutor.setCorePoolSize( properties.getCorePoolSize() != null ? properties.getCorePoolSize() : cpuCores ); // 最大线程数(配置优先,默认CPU核心数*2) taskExecutor.setMaxPoolSize( properties.getMaxPoolSize() != null ? properties.getMaxPoolSize() : cpuCores * 2 ); // 其他固定配置项 taskExecutor.setQueueCapacity(properties.getQueueCapacity()); taskExecutor.setKeepAliveSeconds(properties.getKeepAliveSeconds()); taskExecutor.setThreadNamePrefix(properties.getThreadNamePrefix()); // 拒绝策略保持原样 taskExecutor.setRejectedExecutionHandler( new ThreadPoolExecutor.CallerRunsPolicy() ); taskExecutor.initialize(); return taskExecutor; } }