package com.fjhx.config;

import com.fjhx.constants.ErrorMsgConstant;
import org.springblade.core.log.exception.ServiceException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * 线程池配置
 */
@EnableAsync
@Configuration
public class TaskPoolConfig {

    public static final String excelExecutor = "excelExecutor";

    @Bean(name = excelExecutor)
    public ThreadPoolTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        // 配置核心线程数
        threadPoolTaskExecutor.setCorePoolSize(2);
        // 配置最大线程数
        threadPoolTaskExecutor.setMaxPoolSize(5);
        // 配置队列大小
        threadPoolTaskExecutor.setQueueCapacity(10);
        // 缓冲队列大小
        threadPoolTaskExecutor.setKeepAliveSeconds(10);
        // 配置线程池中的线程的名称前缀
        threadPoolTaskExecutor.setThreadNamePrefix(excelExecutor + "：");
        // 线程池对拒绝任务的处理策略：由调用线程（提交任务的线程）处理该任务
        threadPoolTaskExecutor.setRejectedExecutionHandler((r, executor) -> {
            throw new ServiceException(ErrorMsgConstant.SYSTEM_BUSY_ERROR);
        });

        // 执行初始化
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }

}
