package com.changhu.config;

import com.changhu.common.properties.ThreadProperties;
import jakarta.annotation.Resource;
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;

/**
 * author: luozhun
 * desc: 线程池配置
 * createTime: 2023/8/23 18:12
 */
@Slf4j
@Configuration
@EnableAsync
public class ThreadPollConfig {

    @Resource
    private ThreadProperties threadProperties;

    @Bean
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {

        log.info("已加载 【{}】 的配置 【{}】：", "线 程 池", threadProperties);

        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        // 配置核心线程数
        threadPoolTaskExecutor.setCorePoolSize(threadProperties.getCorePoolSize());
        // 配置最大线程数
        threadPoolTaskExecutor.setMaxPoolSize(threadProperties.getMaxPoolSize());
        // 配置队列大小
        threadPoolTaskExecutor.setQueueCapacity(threadProperties.getQueueCapacity());
        // 配置存活时间
        threadPoolTaskExecutor.setKeepAliveSeconds(threadProperties.getKeepAliveSeconds());
        // 配置线程池中的线程的名称前缀
        threadPoolTaskExecutor.setThreadNamePrefix(threadProperties.getThreadNamePrefix());

        /*
         * rejection-policy：当pool已经达到max size的时候，如何处理新任务?
         *  1.ThreadPoolExecutor.AbortPolicy 丢弃任务并抛出RejectedExecutionException异常(默认)。
         *  2.ThreadPoolExecutor.DiscardPolicy 丢弃任务，但是不抛出异常。
         *  3.ThreadPoolExecutor.DiscardOldestPolicy 丢弃队列最前面的任务，然后重新尝试执行任务
         *  4.ThreadPoolExecutor.CallerRunsPolicy 由调用线程处理该任务
         */
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 执行初始化
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }
}
