1. 程式人生 > >springBoot執行緒池使用

springBoot執行緒池使用

在我們現實開發中肯定會遇到需要延時請求並且高併發的業務場景,所以結合這個我自己寫了一個模擬延時+高併發的小案例供大家參考.

1. 執行緒池相關配置(當然你也可以寫在配置檔案中方便改動,我就先寫死了):

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

import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
public class BeanConfig {

    @Bean
    public TaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 設定核心執行緒數
        executor.setCorePoolSize(5);
        // 設定最大執行緒數
        executor.setMaxPoolSize(10);
        // 設定佇列容量
        executor.setQueueCapacity(20);
        // 設定執行緒活躍時間(秒)
        executor.setKeepAliveSeconds(60);
        // 設定預設執行緒名稱
        executor.setThreadNamePrefix("hello-");
        // 設定拒絕策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任務結束後再關閉執行緒池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        return executor;
    }
}

2. 要進行延時處理並且高併發的業務程式碼:

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;


@Component
public class Test {

    @Async
   public void test(int i){
        SimpleDateFormat format=new SimpleDateFormat("HH:mm:ss");
        try {
            Thread.sleep(10000);
            System.out.println("多執行緒非同步執行"+i+"  "+Thread.currentThread().getName()+"  "+format.format(new Date()));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }



}

3.模擬多個頁面請求後要進行後續邏輯處理:

@GetMapping("/test1")
@ResponseBody
public void test1(){
    for (int i = 0; i < 100; i++) {
         test.test(i);

    }

}

4.執行結果,我設定執行緒池大小為10,業務執行邏輯開始時休眠10秒再執行,你會發現每10秒就會有10個執行緒開始執行業務: