springboot自定義線程池

/**
 * @auther fanxuebo
 * @desc    線程池配置和初始化
 * @Company 
 * @create 2018/12/29 8:23
 */
@Configuration
public class MyExecutorPool {

    @Autowired
    private ThreadPoolProperties threadPoolProperties;

    @Bean(name = "myAsyncThread")
    public ThreadPoolTaskExecutor myTaskAsyncPool() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(threadPoolProperties.getCorePoolSize());//表示線程池核心線程,正常情況下開啓的線程數量。
        executor.setMaxPoolSize(threadPoolProperties.getMaxPoolSize());//當核心線程都在跑任務,還有多餘的任務會存到此處。
        executor.setQueueCapacity(threadPoolProperties.getQueueCapacity());//如果queueCapacity存滿了,還有任務就會啓動更多的線程,直到線程數達到maxPoolSize。如果還有任務,則根據拒絕策略進行處理。
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());//該策略是又調用任務的線程執行。
        executor.setKeepAliveSeconds(threadPoolProperties.getKeepAliveSeconds());//非核心線程的超時時長,超長後會被回收。
        executor.setThreadNamePrefix(threadPoolProperties.getThreadNamePrefix());
        executor.initialize();//初始化線程池。
        return executor;
    }
}

 

/**
 * @auther fanxuebo
 * @desc    配置線程池參數讀取配置文件
 * @Company 
 * @create 2018/12/29 8:27
 */
@ConfigurationProperties("executor")
@Component
public class ThreadPoolProperties {

    private Integer corePoolSize;
    private Integer maxPoolSize;
    private Integer queueCapacity;
    private Integer keepAliveSeconds;
    private String threadNamePrefix;

    public Integer getCorePoolSize() {
        return corePoolSize;
    }

    public void setCorePoolSize(Integer corePoolSize) {
        this.corePoolSize = corePoolSize;
    }

    public Integer getMaxPoolSize() {
        return maxPoolSize;
    }

    public void setMaxPoolSize(Integer maxPoolSize) {
        this.maxPoolSize = maxPoolSize;
    }

    public Integer getQueueCapacity() {
        return queueCapacity;
    }

    public void setQueueCapacity(Integer queueCapacity) {
        this.queueCapacity = queueCapacity;
    }

    public Integer getKeepAliveSeconds() {
        return keepAliveSeconds;
    }

    public void setKeepAliveSeconds(Integer keepAliveSeconds) {
        this.keepAliveSeconds = keepAliveSeconds;
    }

    public String getThreadNamePrefix() {
        return threadNamePrefix;
    }

    public void setThreadNamePrefix(String threadNamePrefix) {
        this.threadNamePrefix = threadNamePrefix;
    }
}

 

配置文件:

executor:
    corePoolSize: 5
    maxPoolSize: 10
    queueCapacity: 20
    keepAliveSeconds: 60
    threadNamePrefix: XCExecutor-

 

在springboot啓動類加@EnableAsync註解,然後在需要多線程執行的方法上加註解@Async(value = "myAsyncThread")即可。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章