/*
 * 文 件 名:  Socket
 * 版    权:  浩鲸云计算科技股份有限公司
 * 描    述:  <描述>
 * 修 改 人:  learshaw
 * 修改时间:  2020/5/25
 * 跟踪单号:  <跟踪单号>
 * 修改单号:  <修改单号>
 * 修改内容:  <修改内容>
 */
package com.ruoyi.ems.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.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Scats socket 链路配置
 * <功能详细描述>
 *
 * @author learshaw
 * @version [版本号, 2021/04/07]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Configuration
public class ThreadConfig {
    private static final Logger log = LoggerFactory.getLogger(ThreadConfig.class);

    @Bean(name = "msgHandleExecutor")
    public ThreadPoolTaskExecutor msgHandleExecutor(@Value("${mqtt.executor.msgHandle.corePoolSize}") int corePoolSize,
        @Value("${mqtt.executor.msgHandle.maxPoolSize}") int maxPoolSize,
        @Value("${mqtt.executor.msgHandle.queueCapacity}") int queueCapacity,
        @Value("${mqtt.executor.msgHandle.namePrefix}") String namePrefix) {
        log.info("start msgHandleExecutor");
        return buildExecutor(corePoolSize, maxPoolSize, queueCapacity, namePrefix,
            new ThreadPoolExecutor.DiscardOldestPolicy());
    }

    private ThreadPoolTaskExecutor buildExecutor(int corePoolSize, int maxPoolSize, int queueCapacity,
        String namePrefix, RejectedExecutionHandler rejectedExecutionHandler) {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //配置核心线程数
        executor.setCorePoolSize(corePoolSize);
        //配置最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        //配置队列大小
        executor.setQueueCapacity(queueCapacity);
        //配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix(namePrefix);

        // 线程池对拒绝任务(无限程可用)的处理策略
        // ThreadPoolExecutor.AbortPolicy:丢弃任务并抛出RejectedExecutionException异常。
        // ThreadPoolExecutor.DiscardPolicy：也是丢弃任务，但是不抛出异常。
        // ThreadPoolExecutor.DiscardOldestPolicy：丢弃队列最前面的任务，然后重新尝试执行任务（重复此过程）
        // ThreadPoolExecutor.CallerRunsPolicy：由调用线程处理该任务,如果执行器已关闭,则丢弃.
        executor.setRejectedExecutionHandler(rejectedExecutionHandler);
        //执行初始化
        executor.initialize();

        return executor;
    }
}