package com.cool.store.executor;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * <p>
 * 线程池配置类
 * </p>
 *
 * @author wangff
 * @since 2025/9/5
 */
@Configuration
public class ThreadPoolTaskConfig {

    /**
     * 通用线程池
     */
    @Bean
    public TaskExecutor generalThreadPool() {
        int cores = Runtime.getRuntime().availableProcessors();

        ThreadPoolTaskExecutor executor = new MdcTaskExecutor();
        // 核心线程数目
        executor.setCorePoolSize(cores*2);
        // 指定最大线程数
        executor.setMaxPoolSize(200);
        // 队列中最大的数目
        executor.setQueueCapacity(5000);
        // 线程名称前缀
        executor.setThreadNamePrefix("generalThreadPool_");
        // 对拒绝task的处理策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 线程空闲后的最大存活时间
        executor.setKeepAliveSeconds(60);
        // 加载
        executor.initialize();
        return executor;
    }
}
