You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
udi-wms-java/src/main/java/com/glxp/api/config/TaskPoolConfig.java

77 lines
2.8 KiB
Java

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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;
}
}