package com.ruoyi.framework.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;

/**
 * TTS 异步任务线程池配置
 *
 * @author ruoyi
 * @date 2026-05-19
 */
@Configuration
@EnableAsync
public class TtsThreadPoolConfig
{
    /**
     * 核心线程池大小
     */
    private static final int CORE_POOL_SIZE = 5;

    /**
     * 最大创建线程数量
     */
    private static final int MAX_POOL_SIZE = 10;

    /**
     * 队列容量
     */
    private static final int QUEUE_CAPACITY = 20;

    /**
     * 线程池维护线程存活时间
     */
    private static final int KEEP_ALIVE_SECONDS = 60;

    /**
     * 线程名称前缀
     */
    private static final String THREAD_NAME_PREFIX = "tts-async-";

    /**
     * TTS 异步任务执行器
     */
    @Bean("ttsTaskExecutor")
    public Executor ttsTaskExecutor()
    {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(CORE_POOL_SIZE);
        executor.setMaxPoolSize(MAX_POOL_SIZE);
        executor.setQueueCapacity(QUEUE_CAPACITY);
        executor.setKeepAliveSeconds(KEEP_ALIVE_SECONDS);
        executor.setThreadNamePrefix(THREAD_NAME_PREFIX);
        // 拒绝策略：由调用线程执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待队列任务完成后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);
        executor.initialize();
        return executor;
    }
}
