package com.yingxin.prms.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Configuration
public class InitAscynTaskThreadPoolConfig {

    private static Logger logger = LoggerFactory.getLogger(InitAscynTaskThreadPoolConfig.class);

    @Value("${ascynTaskThreadPool.corePoolSize}")
    private int CORE_POOL_SIZE;

    @Value("${ascynTaskThreadPool.maxPoolSize}")
    private int MAX_POOL_SIZE;

    @Bean(name = "asyncTaskPool")
    public AsyncTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setThreadNamePrefix("PRMS_POOL-");
        /*
        1）当池子大小小于corePoolSize就新建线程，并处理请求
        2）当池子大小等于corePoolSize，把请求放入workQueue中，池子里的空闲线程就去从workQueue中取任务并处理
        3）当workQueue放不下新入的任务时，新建线程入池，并处理请求，如果池子大小撑到了maximumPoolSize就用RejectedExecutionHandler来做拒绝处理
        4）另外，当池子的线程数大于corePoolSize的时候，多余的线程会等待keepAliveTime长的时间，如果无请求可处理就自行销毁
         */
        logger.info("异步任务线程池核心线程数: {}", CORE_POOL_SIZE);
        logger.info("异步任务线程池最大线程数: {}", MAX_POOL_SIZE);
        executor.setCorePoolSize(CORE_POOL_SIZE);
        executor.setMaxPoolSize(MAX_POOL_SIZE);
        return executor;
    }
}
