package com.sien.common.config;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import tillo.app_ws.model.Constants;

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

/**
 * 异步注解的线程池数量
 */
@Configuration
@ComponentScan("com")
@EnableAsync  //开启异步任务支持如果Application已经开启，则这个可以省略
public class TaskExecutorConfig implements AsyncConfigurer {

    // 此配置可以解决Could not find default TaskExecutor bean的debug异常
    // 实现AsyncConfigurer接口并重写getAsyncExecutor方法，并返回一个ThreadPoolTask​​Executor，
    // 这样我们就获得了一个基于线程池TaskExecutor

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        //当前线程数
        taskExecutor.setCorePoolSize(Constants.CPU_PROCESSORS * 10);
        // 最大线程数
        taskExecutor.setMaxPoolSize(Constants.CPU_PROCESSORS * 30);
        //线程池所使用的缓冲队列
        taskExecutor.setQueueCapacity(2048);
        // 空闲线程存活时间
        taskExecutor.setKeepAliveSeconds(0);
        //  线程名称前缀
        taskExecutor.setThreadNamePrefix("MyAsync-");

        // rejection-policy：当pool已经达到max size的时候，如何处理新任务
        // CALLER_RUNS：不在新线程中执行任务，而是有调用者所在的线程来执行
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 执行初始化
        taskExecutor.initialize();
        return taskExecutor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return null;
    }
}