package com.seer.teach.openapi.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

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

/**
 * 全局异步线程池与 MVC 异步支持配置
 * <p>
 * 解决：
 * - Streaming through a reactive type requires an Executor to write to the response.
 * - 提供日志与异步任务共用线程池
 *
 * @author Captain
 * @since 2025-09-10
 */
@Slf4j
@Configuration
public class AsyncConfig {

    /**
     * 【业务异步日志线程池】
     * 用于系统日志或异步任务等场景
     */
    @Bean("logExecutor")
    public Executor logExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(20);
        executor.setQueueCapacity(200);
        executor.setKeepAliveSeconds(60);
        executor.setThreadNamePrefix("log-async-");

        // 拒绝策略：调用者线程执行，避免任务丢失
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        log.info("初始化异步线程池 [logExecutor]：corePoolSize={}, maxPoolSize={}, queueCapacity={}",
                executor.getCorePoolSize(), executor.getMaxPoolSize(), executor.getQueueCapacity());
        // JVM 优雅关闭钩子
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            log.info("正在关闭异步线程池 [logExecutor]...");
            executor.shutdown();
            log.info("异步线程池 [logExecutor] 已关闭");
        }));

        return executor;
    }

}
