package com.greenorange.promotion.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


@Data
@Configuration
@ConfigurationProperties(prefix = "threadpool")
public class ThreadPoolConfig {

    // 从配置文件中读取线程池的配置参数
    private int corePoolSize; // 核心线程数

    private int maxPoolSize; // 最大线程数

    private int queueCapacity; // 队列容量

    private long keepAliveTime; // 线程空闲时间，单位秒

    /**
     * 配置线程池
     * @return 线程池实例
     */
    @Bean
    public ExecutorService threadPoolExecutor() {
        return new ThreadPoolExecutor(
                corePoolSize,           // 核心线程数
                maxPoolSize,            // 最大线程数
                keepAliveTime,          // 空闲线程存活时间
                TimeUnit.SECONDS,       // 空闲时间单位
                new LinkedBlockingQueue<>(queueCapacity), // 任务队列，设置队列大小
                new ThreadPoolExecutor.CallerRunsPolicy() // 拒绝策略：调用者运行
        );
    }
}
