1. 程式人生 > 實用技巧 >SpringBoot - 使用ExecutorService執行緒池執行非同步任務教程(Runnable任務為例)

SpringBoot - 使用ExecutorService執行緒池執行非同步任務教程(Runnable任務為例)

在系統需要進行一些比較耗時的操作,比如使用者註冊後要呼叫郵件伺服器給使用者傳送個郵件,又比如上傳一個大資料量的excel並匯入到資料庫。如果後端的這些工作比較耗時,那麼前臺的頁面便會一直處於等待狀態,讓使用者會以為頁面卡死了。

通常這種比較耗時的操作應該做非同步處理,也就是在後臺進行,而使用者可以不用等待。下面通過樣例演示Spring Boot中如何執行非同步任務。

1,開啟執行緒池

這裡我們使用java執行緒池ExecutorService,首先在專案中新增如下配置類,其作用在於Spring啟動時自動載入一個ExecutorService物件。

1 2 3 4 5 6 7 8 @Configuration publicclassThreadPoolConfig { @Bean publicExecutorService executorService() { returnExecutors.newCachedThreadPool(); } }

2,建立非同步任務

這裡我們實現Runnable介面來建立一個非同步任務,裡面程式碼很簡單,就是等待個5秒再結束:

注意:Runnable和Callable在非同步任務中的應用差別在於,一個不帶返回值,一個帶返回值而已。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 publicclassEmailRunnableimplementsRunnable { privateString name; publicEmailRunnable(String name) { this.name = name; } @Override publicvoidrun() { System.out.println("正在給"+ name +"傳送郵件......"); try{ Thread.sleep(5000); }catch(InterruptedException e) { e.printStackTrace(); } System.out.println("郵件傳送完畢"
); } }

3,執行非同步任務

(1)這裡我們在一個Cotroller中通過執行緒池執行這個非同步任務:
1 2 3 4 5 6 7 8 9 10 11 12 13 @RestController publicclassHelloController { @Autowired ExecutorService executorService; @GetMapping("/hello") publicvoidhello() { System.out.println("hello start"); executorService.execute(newEmailRunnable("hangge")); System.out.println("hello end"); } }


(2)通過瀏覽器訪問/hello介面,可以看到控制檯輸出如下: