package com.app.config;

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;

/**
 * 异步线程池
 */
@Configuration
@EnableAsync
public class ThreadPoolConfig {
    /**
     * 核心线程数（默认线程数）
     */
    private static final int core_pool_size = 5;
    /**
     * 最大线程数
     */
    private static final int max_pool_size = 100;
    /**
     * 允许线程空闲时间（单位：默认为秒）
     */
    private static final int keep_alive_time = 10;
    /**
     * 缓冲队列数
     */
    private static final int queue_capacity = 200;
    /**
     * 线程池名前缀
     */
    private static final String thread_name_prefix = "Async-Service-";

    /**
     * bean的名称，默认为首字母小写的方法名
     *
     * @return
     */
    @Bean("taskExecutor")
    public ThreadPoolTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(core_pool_size);
        executor.setMaxPoolSize(max_pool_size);
        executor.setQueueCapacity(queue_capacity);
        executor.setKeepAliveSeconds(keep_alive_time);
        executor.setThreadNamePrefix(thread_name_prefix);

        // 线程池对拒绝任务的处理策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 初始化
        executor.initialize();
        return executor;
    }

}
