package com.ema.admin.config;

import com.ema.common.consts.CommonConst;
import lombok.extern.slf4j.Slf4j;
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.ThreadPoolExecutor;

/**
 * 异步线程配置类
 * 参考文档：https://www.xncoding.com/2017/07/20/spring/sb-async.html
 *
 * @author LJ
 */
@Slf4j
@Configuration
@EnableAsync
public class AsyncExecutorConfig {

    @Bean(name = CommonConst.ASYNC_POOL)
    public ThreadPoolTaskExecutor asyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 线程池维护线程的最少数量
        executor.setCorePoolSize(8);
        // 线程池维护线程的最大数量,只有在缓冲队列满了之后才会申请超过核心线程数的线程
        executor.setMaxPoolSize(32);
        // 缓存队列
        executor.setQueueCapacity(64);
        // 允许的空闲时间,当超过了核心线程出之外的线程在空闲时间到达之后会被销毁
        executor.setKeepAliveSeconds(60);

        // 线程池对拒绝任务（无线程可用）的处理策略，目前只支持AbortPolicy、CallerRunsPolicy；默认为后者
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 表明等待所有线程执行完，默认为false
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 等待时长
        executor.setAwaitTerminationSeconds(600);
        // 线程名称前缀
        executor.setThreadNamePrefix(CommonConst.ASYNC_POOL + "-");
        executor.initialize(); // 如果不初始化，导致找到不到执行器
        return executor;
    }

    /**
     * 回调处理专用线程池
     * 针对高并发场景（1000+）优化配置
     */
    @Bean(name = "callbackExecutor")
    public ThreadPoolTaskExecutor callbackExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数，满足高并发处理
        executor.setCorePoolSize(20);
        // 最大线程数
        executor.setMaxPoolSize(100);
        // 队列容量，积压更多任务
        executor.setQueueCapacity(1000);
        // 空闲线程存活时间
        executor.setKeepAliveSeconds(60);

        // 拒绝策略：由调用线程执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(600);
        executor.setThreadNamePrefix("callback-");
        executor.initialize();
        return executor;
    }

}