package com.cusc.nirvana.user.rnr.fp.common.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.ArrayBlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 异步线程池配置
 */
@Configuration
@EnableAsync
public class ExecutorIssueConfig {
    private final static Logger LOGGER = LoggerFactory.getLogger(ExecutorIssueConfig.class);


    /**
     * 上报线程池
     */
    @Bean("uploadIssueExecutor")
    public Executor uploadExecutor() {
        LOGGER.info("init uploadIssueExecutor");

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //配置核心线程数
        executor.setCorePoolSize(2);
        //配置最大线程数
        executor.setMaxPoolSize(10);
        //配置队列大小
        executor.setQueueCapacity(100);
        //允许线程的空闲时间60秒：当超过了核心线程之外的线程在空闲时间到达之后会被销毁
        executor.setKeepAliveSeconds(60);
        //配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix("fp-uploadIssue");

        //线程池的饱和策略,满了直接丢弃。 任务已经先入库了，并有定时任务执行。这列可以直接丢弃。
        //AbortPolicy：直接抛出异常，这是默认策略；
        //CallerRunsPolicy：用调用者所在的线程来执行任务；
        //DiscardOldestPolicy：丢弃阻塞队列中靠最前的任务，并执行当前任务；
        //DiscardPolicy：直接丢弃任务；
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
        //线程池的优雅关闭,表明等待所有线程执行完
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //执行初始化
        executor.initialize();
        return executor;
    }

	@Bean
	public Executor fpExecutorService(){
		return new ThreadPoolExecutor(6,60,60,TimeUnit.SECONDS,
				new ArrayBlockingQueue<>(60), new ThreadPoolExecutor.CallerRunsPolicy());
	}
}
