package com.css.simulation.resource.scheduler.infra.configuration.pool;

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.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Data
@EnableAsync
@Configuration
@ConfigurationProperties(prefix = "pool")
public class PoolConfiguration {

    private PoolParam pool1;
    /**
     * 在方法上使用 @Async("线程池名称")
     */
    @Bean(name = "pool1")
    public ThreadPoolTaskExecutor pool1() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setThreadNamePrefix(pool1.getThreadNamePrefix());
        threadPoolTaskExecutor.setCorePoolSize(pool1.getCorePoolSize());
        threadPoolTaskExecutor.setMaxPoolSize(pool1.getMaxPoolSize());
        threadPoolTaskExecutor.setQueueCapacity(pool1.getQueueCapacity());
        threadPoolTaskExecutor.setKeepAliveSeconds(3);
        // rejection-policy：当pool已经达到max size的时候，如何处理新任务
        // CALLER_RUNS：不在新线程中执行任务，而是由调用者所在的线程来执行
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        // 加载
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }
}
