ExecutorConfig.java 1.75 KB
Newer Older
zp's avatar
zp committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
package com.tanpu.fund.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
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.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置类
 */
@Configuration
@EnableAsync
@Slf4j
public class ExecutorConfig {

    @Value("${task.core_pool_size}")
    private int taskCorePoolSize;
    @Value("${task.max_pool_size}")
    private int taskMaxPoolSize;
    @Value("${task.queue_capacity}")
    private int taskQueueCapacity;
    @Value("${task.thread_name_prefix}")
    private String taskThreadNamePrefix;

    @Bean(name = "asyncTaskExecutor")
    public Executor asyncTaskExecutor() {
        log.info("start asyncUbrScanExecutor");
        ThreadPoolTaskExecutor executor = new VisiableThreadPoolTaskExecutor();
        //配置核心线程数
        executor.setCorePoolSize(taskCorePoolSize);
        //配置最大线程数
        executor.setMaxPoolSize(taskMaxPoolSize);
        //配置队列大小
        executor.setQueueCapacity(taskQueueCapacity);
        //配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix(taskThreadNamePrefix);

        // rejection-policy:当pool已经达到max size的时候,如何处理新任务
        // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //执行初始化
        executor.initialize();
        return executor;
    }
}