package com.xx.xx.config;
import java.util.concurrent.ThreadPoolExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
/**
* 线程池配置
*
* @author jiangkd
* @date 2022/7/14 14:30
*/
@Configuration
public class ThreadPoolTaskExecutorConfig {
final private Logger log = LoggerFactory.getLogger(this.getClass());
/**
* 线程池, ThreadPoolTaskExecutor
* <p>
* ThreadPoolTaskExecutor实质是对ThreadPoolExecutor的封装
* 线程池说明以及参数参考: https://www.cnblogs.com/no-celery/p/16355344.html
*
* @return ThreadPoolTaskExecutor
*/
@Bean
public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
//
final ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
// 最佳线程数目 =((线程等待时间+线程CPU时间)/线程CPU时间 )*CPU数目
// 核心线程池大小
threadPoolTaskExecutor.setCorePoolSize(8);
// 最大线程数
threadPoolTaskExecutor.setMaxPoolSize(16);
// 线程池维护线程(不包括核心线程)所允许的空闲时间, 秒
threadPoolTaskExecutor.setKeepAliveSeconds(100);
// 队列最大长度
threadPoolTaskExecutor.setQueueCapacity(30);
// 线程池关闭的时候等待所有任务都完成后, 再继续销毁其他的Bean
threadPoolTaskExecutor.setWaitForTasksToCompleteOnShutdown(true);
// 线程池中任务销毁的等待时间, 如果超过这个时间还没有销毁就强制销毁, 以确保应用最后能够被关闭, 而不是阻塞住
threadPoolTaskExecutor.setAwaitTerminationSeconds(60);
// 如果为true, 核心线程空闲时间到达setKeepAliveSeconds秒后会被销毁
threadPoolTaskExecutor.setAllowCoreThreadTimeOut(false);
// 线程前缀名称, 方便定位处理任务所在的线程池
threadPoolTaskExecutor.setThreadNamePrefix("ct-logic-task-");
/*
拒绝策略
采用默认策略, 线程池和队列都满了的时候, 丢弃任务 && 直接抛出java.util.concurrent.RejectedExecutionException异常
*/
threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
// 初始化线程池
threadPoolTaskExecutor.initialize();
log.info("自定义线程池, ThreadPoolTaskExecutor线程池初始化 ... SUCCESS");
return threadPoolTaskExecutor;
}
}