package com.zcloud.safetyDutyList.config;

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.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author zhangyue
 * @date 2026/2/2 17:24
 */

@Configuration
public class ThreadPoolAsyncConfig {


    public static Integer maxPoolSize;
    public static Integer corePoolSize;
    public static Integer queueCapacity;
    public static String namePrefix;
    public static Integer keepAliveSeconds;

    @Value("${archives.async.pool.maxPoolSize}")
    public void setMaxPoolSize(Integer maxPoolSizeProperties) {
        maxPoolSize = maxPoolSizeProperties;
    }

    @Value("${archives.async.pool.corePoolSize}")
    public void setCorePoolSize(Integer corePoolSizeProperties) {
        corePoolSize = corePoolSizeProperties;
    }

    @Value("${archives.async.pool.queueCapacity}")
    public void setQueueCapacity(Integer queueCapacityProperties) {
        queueCapacity = queueCapacityProperties;
    }

    @Value("${archives.async.pool.namePrefix}")
    public void setNamePrefix(String namePrefixProperties) {
        namePrefix = namePrefixProperties;
    }

    @Value("${archives.async.pool.keepAliveSeconds}")
    public void setKeepAliveSeconds(Integer keepAliveSecondsProperties) {
        keepAliveSeconds = keepAliveSecondsProperties;
    }

    @Bean()
    public Executor asyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        //核心线程数
        executor.setCorePoolSize(corePoolSize);
        //任务队列的大小
        executor.setQueueCapacity(queueCapacity);
        //线程前缀名
        executor.setThreadNamePrefix(namePrefix);
        //线程存活时间
        executor.setKeepAliveSeconds(keepAliveSeconds);
        /**
         * 拒绝处理策略
         * CallerRunsPolicy()：交由调用方线程运行，比如 main 线程。
         * AbortPolicy()：直接抛出异常。
         * DiscardPolicy()：直接丢弃。
         * DiscardOldestPolicy()：丢弃队列中最老的任务。
         */
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        // 初始化
        executor.initialize();
        return executor;
    }
}
