spring boot 線程池配置


1.配置類

package cn.com.bonc.util;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Configuration
@EnableAsync
public class MyThread {

    private int corePoolSize = 10;//線程池維護線程的最少數量

    private int maxPoolSize = 30;//線程池維護線程的最大數量

    private int queueCapacity = 8; //緩存隊列

    private int keepAlive = 60;//允許的空閑時間

    @Bean
    public Executor myExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setThreadNamePrefix("mqExecutor-");
     // rejection-policy:當pool已經達到max size的時候,如何處理新任務  
        // CALLER_RUNS:不在新線程中執行任務,而是由調用者所在的線程來執行  executor.setRejectedExecutionHandler(
new ThreadPoolExecutor.CallerRunsPolicy()); //對拒絕task的處理策略 executor.setKeepAliveSeconds(keepAlive); executor.initialize(); return executor; } }

2.注解使用

@Async("myExecutor") //配置類中的方法名

 3.啟動類添加

@EnableAsync

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM