Springboot中使用線程池的三種方式

来源:https://www.cnblogs.com/LoveBB/archive/2023/09/19/17713614.html
-Advertisement-
Play Games

前言 多線程是每個程式員的噩夢,用得好可以提升效率很爽,用得不好就是埋汰的火葬場。 這裡不深入介紹,主要是講解一些標準用法,熟讀唐詩三百首,不會作詩也會吟。 這裡就介紹一下springboot中的多線程的使用,使用線程連接池去非同步執行業務方法。 由於代碼中包含詳細註釋,也為了保持文章的整潔性,我就不 ...


前言

  • 多線程是每個程式員的噩夢,用得好可以提升效率很爽,用得不好就是埋汰的火葬場。
  • 這裡不深入介紹,主要是講解一些標準用法,熟讀唐詩三百首,不會作詩也會吟。
  • 這裡就介紹一下springboot中的多線程的使用,使用線程連接池去非同步執行業務方法。
  • 由於代碼中包含詳細註釋,也為了保持文章的整潔性,我就不過多的做文字描述了。

VisiableThreadPoolTaskExecutor 編寫

  • new VisiableThreadPoolTaskExecutor() 方式創建線程池, 返回值是 Executor
點擊查看代碼

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.concurrent.ListenableFuture;

import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author love ice
 * @create 2023-09-19 0:17
 */
@Slf4j
public class VisiableThreadPoolTaskExecutor extends ThreadPoolTaskExecutor {
    @Override
    public void execute(Runnable task){
        showThreadPoolInfo("execute一個參數的方法執行");
    }

    @Override
    public void execute(Runnable task, long startTimeout){
        showThreadPoolInfo("execute兩個參數的方法執行");
    }

    @Override
    public Future<?> submit(Runnable task){
        showThreadPoolInfo("submit Runnable task 入參方法執行");
        return super.submit(task);
    }

    @Override
    public <T> Future<T> submit(Callable<T> task){
        showThreadPoolInfo("submit Callable<T> task 入參方法執行");
        return super.submit(task);
    }

    @Override
    public ListenableFuture<?> submitListenable(Runnable task){
        showThreadPoolInfo("submitListenable(Runnable task) 方法執行");
        return super.submitListenable(task);
    }

    @Override
    public <T>ListenableFuture<T> submitListenable(Callable<T> task){
        showThreadPoolInfo("submitListenable(Callable<T> task) 方法執行");
        return super.submitListenable(task);
    }

    private void showThreadPoolInfo(String prefix){
        ThreadPoolExecutor threadPoolExecutor = getThreadPoolExecutor();
        log.info("{}, {}, taskCount[{}], completedTaskCount[{}], activeCount[{}], queueSize[{}]",
                this.getThreadNamePrefix(), prefix, threadPoolExecutor.getTaskCount(),
                threadPoolExecutor.getCompletedTaskCount(), threadPoolExecutor.getActiveCount(),
                threadPoolExecutor.getQueue().size());
    }
}

ThreadExceptionLogHandler 編寫

  • 主要用於線程池出現異常時的捕獲
點擊查看代碼
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author love ice
 * @create 2023-09-19 0:13
 */
@Slf4j
@Component
public class ThreadExceptionLogHandler implements Thread.UncaughtExceptionHandler {

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        log.error("[{}]線程池異常,異常信息為:{}",t.getName(),e.getMessage(),e);
    }
}

ExecutorConfig 編寫

  • 核心配置類
點擊查看代碼

import com.test.redis.Infrastructure.handler.ThreadExceptionLogHandler;
import org.springframework.beans.factory.annotation.Autowired;
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 java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 線程池配置
 *
 * @author love ice
 * @create 2023-09-19 0:09
 */
@Configuration
@EnableAsync
public class ExecutorConfig {
    @Value("${thread.pool.coreSize:50}")
    private int coreSize;
    @Value("${thread.pool.maxSize:50}")
    private int maxSize;
    @Value("${thread.pool.queueSize:9999}")
    private int queueSize;
    @Value("${thread.pool.threadNamePrefix:thread-name}")
    private String threadNamePrefix;
    @Value("${thread.pool.keepAlive:60}")
    private int keepAlive;
    @Autowired
    private ThreadExceptionLogHandler threadExceptionLogHandler;

    /**
     * 方式一: new VisiableThreadPoolTaskExecutor() 方式創建線程池,返回值是 Executor
     * 適用於 @Async("asyncServiceExecutor") 註解
     * 也可以
     *  @Autowired
     *  private Executor asyncServiceExecutor;
     *
     * @return Executor
     */
    @Bean
    public Executor asyncServiceExecutor() {
        VisiableThreadPoolTaskExecutor executor = new VisiableThreadPoolTaskExecutor();
        // 配置核心線程數 50
        executor.setCorePoolSize(coreSize);
        // 配置最大線程數 50
        executor.setMaxPoolSize(maxSize);
        // 配置隊列大小 9999
        executor.setQueueCapacity(queueSize);
        // 配置線程池中的線程名稱首碼 模塊-功能-作用
        executor.setThreadNamePrefix(threadNamePrefix);
        // rejection-policy:當pool已經達到max size的時候,如何處理新任務
        // CALLER_RUNS:不在新線程中執行任務,而是有調用者所在的線程來執行
        // 線程池無法接受新的任務並且隊列已滿時,如果有新的任務提交給線程池,而線程池已經達到了最大容量限制,那麼這個任務不會被丟棄,而是由調用該任務的線程來執行。
        // 這樣可以避免任務被直接丟棄,並讓調用者自己執行任務以減輕任務提交頻率。
        // 這個拒絕策略可能會導致任務提交者的線程執行任務,這可能會對調用者的性能產生一些影響,因為調用者線程需要等待任務執行完成才能繼續進行其他操作。
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 線程空閑後的最大存活時間 60
        executor.setKeepAliveSeconds(keepAlive);
        // 執行初始化
        executor.initialize();
        return executor;
    }

    /**
     * 方式二: new ThreadPoolExecutor() 方式創建線程池
     * 適用於:
     * @Autowired
     * private ExecutorService fbWorkerPool;
     * @return ExecutorService
     */
    @Bean
    public ExecutorService workerPool() {
        return new ThreadPoolExecutor(coreSize, maxSize, keepAlive, TimeUnit.MILLISECONDS,
                new LinkedBlockingDeque<>(20000),
                new ThreadFactory() {
                    private final AtomicInteger threadNumber = new AtomicInteger(1);
                    @Override
                    public Thread newThread(Runnable runnable) {
                        Thread thread = new Thread(runnable, threadNamePrefix + threadNumber.getAndIncrement());
                        thread.setUncaughtExceptionHandler(threadExceptionLogHandler);
                        return thread;
                    }
                });
    }
}

ExecutorController 編寫

  • 演示demo,三種不同的用法, 足以涵蓋大部分場景
點擊查看代碼

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;

/**
 * 這裡是demo演示、把業務寫在 controller 了,一般開發都是在 service 層實現的。
 *
 * @author love ice
 * @create 2023-09-19 0:59
 */
@RestController
@RequestMapping("/executor")
public class ExecutorController {


    /**
     * demo1: 使用非同步註解 @Async("asyncServiceExecutor") 執行方法,適用於沒有返回值的情況下
     */
    public void asyncDemo1() {
        // 假設這是從資料庫查詢出來的數據
        List<String> nameList = new ArrayList<>(Arrays.asList("張三", "李四", "王五"));
        // 把 nameList 進行切分
        int j = 0, size = nameList.size(), batchSize = 10;
        List<List<String>> list = new ArrayList<>();
        while (j < size) {
            List<String> batchList = nameList.stream().skip(j).limit(Math.min(j + batchSize, size) - j).collect(Collectors.toList());
            list.add(batchList);
            j += batchSize;
        }

        // 先把 list 切分成小份數據,在使用 @Async(),非同步處理數據
        list.stream().parallel().forEach(this::asynchronousAuthorization1);
    }

    /**
     * 非同步註解處理業務邏輯,實際業務開發,需要提取到 Service 層,否則會報錯。
     *
     * @param paramList 入參
     */
    @Async("asyncServiceExecutor")
    public void asynchronousAuthorization1(List<String> paramList) {
        paramList.forEach(System.out::println);
        System.out.println("非同步執行 paramList 業務邏輯");
    }

//================================分隔符======================

    @Autowired
    private ExecutorService workerPool;

    /**
     * demo2: workerPool.execute() 實現非同步邏輯。適用於沒有返回值的情況下
     */
    public void asyncDemo2() {
        // 假設這是從資料庫查詢出來的數據
        List<String> nameList = new ArrayList<>(Arrays.asList("張三", "李四", "王五"));
        // 把 nameList 進行切分
        int j = 0, size = nameList.size(), batchSize = 10;
        List<List<String>> list = new ArrayList<>();
        while (j < size) {
            List<String> batchList = nameList.stream().skip(j).limit(Math.min(j + batchSize, size) - j).collect(Collectors.toList());
            list.add(batchList);
            j += batchSize;
        }

        // 將 list 切分成小份數據,workerPool.execute(),非同步處理數據
        list.stream().parallel().forEach(paramList->{
            workerPool.execute(()->asynchronousAuthorization2(paramList));
        });
    }

    public void asynchronousAuthorization2(List<String> paramList) {
        paramList.forEach(System.out::println);
        System.out.println("非同步執行 paramList 業務邏輯");
    }


//================================分隔符======================


    /**
     * demo3: futures.add() 實現非同步邏輯。適用於有返回值的情況下
     */
    public void asyncDemo3() {
        // 假設這是從資料庫查詢出來的數據
        List<String> nameList = new ArrayList<>(Arrays.asList("張三", "李四", "王五"));
        // 把 nameList 進行切分
        int j = 0, size = nameList.size(), batchSize = 10;
        List<List<String>> list = new ArrayList<>();
        while (j < size) {
            List<String> batchList = nameList.stream().skip(j).limit(Math.min(j + batchSize, size) - j).collect(Collectors.toList());
            list.add(batchList);
            j += batchSize;
        }

        List<CompletableFuture<String>> futures = new ArrayList<>();
        // 將 list 切分成小份數據,futures.add(),非同步處理數據,有返回值的情況下
        list.forEach(paramList->{
            // CompletableFuture.supplyAsync() 該任務會在一個新的線程中執行,並返回一個結果
            // 通過futures.add(...)將這個非同步任務添加到futures列表中。這樣可以方便後續對多個非同步任務進行管理和處理
            futures.add(CompletableFuture.supplyAsync(() -> {
                asynchronousAuthorization3(paramList);
               return "預設值";
            }, workerPool));

            // 防止太快,讓它休眠一下
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

        //new CompletableFuture[0] 創建了一個初始長度為 0 的 CompletableFuture 數組,作為目標數組。然後,futures.toArray(new CompletableFuture[0]) 將 futures 列表中的元素複製到目標數組中,並返回結果數組。
        CompletableFuture<String>[] futuresArray = futures.toArray(new CompletableFuture[0]);
        // 通過將多個非同步任務添加到futures列表中,我們可以使用CompletableFuture提供的方法來對這些非同步任務進行組合、等待和處理。
        // 例如使用CompletableFuture.allOf(...)等待所有任務完成,或者使用CompletableFuture.join()獲取單個任務的結果等。
        CompletableFuture.allOf(futures.toArray(futuresArray)).join();

        // 獲取每個任務的結果或處理異常
        List<String> results = new ArrayList<>();
        for (CompletableFuture<String> future :futuresArray) {
            // 處理任務的異常
            future.exceptionally(ex -> {
                System.out.println("Task encountered an exception: " + ex.getMessage());
                return "0"; // 返回預設值或者做其他補償操作
            });

            // 獲取任務結果
            String result = future.join();
            results.add(result);
        }
        // 所有任務已完成,可以進行下一步操作
    }

    public void asynchronousAuthorization3(List<String> paramList) {
        paramList.forEach(System.out::println);
        System.out.println("非同步執行 paramList 業務邏輯");
    }
}

作者:天下沒有收費的bug 出處:https://www.cnblogs.com/LoveBB/ 本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須在文章頁面給出原文鏈接,否則保留追究法律責任的權利。
您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • Ubuntu20.04安裝Postgres主從備份 一.查看可安裝的Postgres包 #列出相關的軟體包,這裡安裝的是14版本 apt list | grep -w postgresql-14 | tail -1 #下載Postgres apt install -y postgresql-14/f ...
  • 基於OpenHarmony和華為雲平臺打造的智能家居設備,分別為智能門鎖,儲物精靈 NFC版,儲物精靈Pro版三個設備。 ...
  • 之前在 《iOS16新特性:靈動島適配開發與到家業務場景結合的探索實踐》 里介紹了iOS16新的特性:實時更新(Live Activity)中靈動島的適配流程,但其實除了靈動島的展示樣式,Live Activity還有一種非常實用的應用場景,那就是鎖屏界面實時狀態更新: ...
  • 前端遠程調試方案 Chii 的使用經驗分享 Chii 是與 weinre 一樣的遠程調試工具 ,主要是將 web inspector 替換為最新的 chrome devtools frontend 監控列表頁面可以看到網站的標題鏈接,IP,useragent,可以快速定位調試頁面,監控頁信息完善,支 ...
  • 這裡給大家分享我在網上總結出來的一些知識,希望對大家有所幫助 JavaScript 語言的內核足夠大,導致我們很容易誤解它的某些部分是如何工作的。我最近重構了一些使用 every ()方法的代碼,並且發現我並不真正理解every()的邏輯。在我看來,我認為回調函數必須被調用並返回 true的時候ev ...
  • 今天在維護優化公司中台項目時,發現路由的文件配置非常多非常亂,只要只中大型項目,都會進入很多的路由頁面,規範一點的公司還會吧路由進行模塊化導入,但是依然存在很多文件夾的和手動導入的問題。 於是我想到了我之前使用vuex時進行的模塊化自動導入js文件,能不能使用到自動導入.vue文件中去,答案是可以! ...
  • ES 2023新特性速解 一、新增數組方法 操作數組的方法 Array.prototype.toSorted(compareFn) //返回一個新數組,其中元素按升序排序,而不改變原始數組。 Array.prototype.toReversed() //返回一個新數組,該數組的元素順序被反轉,但不改 ...
  • 這是一個講解DDD落地的文章系列,作者是《實現領域驅動設計》的譯者滕雲。本文章系列以一個真實的並已成功上線的軟體項目——碼如雲(https://www.mryqr.com)為例,系統性地講解DDD在落地實施過程中的各種典型實踐,以及在面臨實際業務場景時的諸多取捨。 本系列包含以下文章: DDD入門 ...
一周排行
    -Advertisement-
    Play Games
  • WPF本身不支持直接的3D繪圖,但是它提供了一些用於實現3D效果的高級技術。 如果你想要在WPF中進行3D繪圖,你可以使用兩種主要的方法: WPF 3D:這是一種在WPF應用程式中創建3D圖形的方式。WPF 3D提供了一些基本的3D形狀(如立方體、球體和錐體)以及一些用於控制3D場景和對象的工具(如 ...
  • 一、XML概述 XML(可擴展標記語言)是一種用於描述數據的標記語言,旨在提供一種通用的方式來傳輸和存儲數據,特別是Web應用程式中經常使用的數據。XML並不預定義標記。因此,XML更加靈活,並且可以適用於廣泛的應用領域。 XML文檔由元素(element)、屬性(attribute)和內容(con ...
  • 從今年(2023)三月份開始,Github開始強制用戶開啟兩步驗證2FA(雙因數)登錄驗證,毫無疑問,是出於安全層面的考慮,畢竟Github賬號一旦被盜,所有代碼倉庫都會毀於一旦,關於雙因數登錄的必要性請參見:別讓你的伺服器(vps)淪為肉雞(ssh暴力破解),密鑰驗證、雙向因數登錄值得擁有。 雙因 ...
  • 第一題 下列代碼輸入什麼? public class Test { public static Test t1 = new Test(); { System.out.println("blockA"); } static { System.out.println("blockB"); } publi ...
  • 本文主要涉及的問題:用ElementTree和XPath讀寫XML文件;解決ElementTree新增元素後再寫入格式不統一的問題;QTableWidget單元格設置控制項 ...
  • QStandardItemModel 類作為標準模型,主打“類型通用”,前一篇水文中,老周還沒提到樹形結構的列表,本篇咱們就好好探討一下這貨。 還是老辦法,咱們先做示例,然後再聊知識點。下麵這個例子,使用 QTreeView 組件來顯示數據,使用的列表模型比較簡單,只有一列。 #include <Q ...
  • 一、直充內充(充值方式) 直充: 包裝套餐直接充值到上游API系統。【PID/Smart】 (如:支付寶、微信 話費/流量/語音/簡訊 等 充值系統)。 內充(套餐打包常見物聯卡系統功能): 套餐包裝 適用於不同類型套餐 如 流量、簡訊、語音 等。 (目前已完善流量邏輯) 二、套餐與計費產品 計費產 ...
  • 在前面幾天中,我們學習了Dart基礎語法、可迭代集合,它們是Flutter應用研發的基本功。今天,我們繼續學習Flutter應用另一個必須掌握知識點:非同步編程(即Future和async/await)。它類似於Java中的FutureTask、JavaScript中的Promise。它是後續Flut... ...
  • 針對改動範圍大、影響面廣的需求,我通常會問上線了最壞情況是什麼?應急預案是什麼?你帶開關了嗎?。當然開關也是有成本的,接下來本篇跟大家一起交流下高頻發佈支撐下的功能開關技術理論與實踐結合的點點滴滴。 ...
  • 1.d3.shuffle D3.shuffle() 方法用於將數組中的元素隨機排序。它使用 Fisher–Yates 洗牌演算法,該演算法是無偏的,具有最佳的漸近性能(線性時間和常數記憶體)。 D3.shuffle() 方法的語法如下: d3.shuffle(array, [start, end]) 其中 ...