package com.ruoyi.ccdi.project.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 异步线程池配置
 *
 * @author ruoyi
 * @date 2026-03-05
 */
@Configuration
@EnableAsync
public class AsyncThreadPoolConfig {

    /**
     * 文件上传专用线程池
     * 容量：100个线程
     * 拒绝策略：AbortPolicy（直接拒绝，由调度线程捕获并重试）
     */
    @Bean("fileUploadExecutor")
    public Executor fileUploadExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数
        executor.setCorePoolSize(100);
        // 最大线程数
        executor.setMaxPoolSize(100);
        // 队列容量（设为0，不使用队列，直接走拒绝策略）
        executor.setQueueCapacity(0);
        // 线程名称前缀
        executor.setThreadNamePrefix("file-upload-");
        // 拒绝策略：AbortPolicy，抛出 RejectedExecutionException
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        // 线程空闲时间（秒）
        executor.setKeepAliveSeconds(60);
        // 等待所有任务完成后再关闭
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 最长等待时间
        executor.setAwaitTerminationSeconds(60);
        executor.initialize();
        return executor;
    }
}
