今天一起學習下如何在spring中進行異步編程。我們都知道,web服務器處理請求 request
的線程是從線程池中獲取的,這也不難解釋,因為當web請求并發數非常大時,如何一個請求進來就創建一條處理線程,由于創建線程和線程上下文切換的開銷是比較大的,web服務器最終將面臨崩潰。另外,web服務器創建的處理線程從頭到尾默認是同步執行的,也就是說,假如處理線程a負責處理請求b,那么當b沒有 return
之前,處理線程a是不可以脫身去處理別的請求的,這將極大限制了web服務器的并發處理能力。
因此線程池解決了線程可循環利用的問題,那同步處理請求怎么去解決呢?答案是異步處理。什么是異步處理呢?異步處理主要是讓上面的b請求處理完成之前,能夠將a線程空閑出來繼續去處理別的請求。那么我們可以這樣做,在a線程內部重新開啟一個線程c去執行任務,讓a直接返回給web服務器,繼續接受新進來的請求。
在開始下面的講解之前,我在這里先區別下兩個概念:
1、處理線程
處理線程屬于web服務器,負責處理用戶請求,采用線程池管理
2、異步線程
異步線程屬于用戶自定義的線程,可采用線程池管理
spring中提供了對異步任務的支持,采用 webasynctask
類即可實現異步任務,同時我們也可以對異步任務設置相應的回調處理,如當任務超時、拋出異常怎么處理等。異步任務通常非常實用,比如我們想讓一個可能會處理很長時間的操作交給異步線程去處理,又或者當一筆訂單支付完成之后,開啟異步任務查詢訂單的支付結果。
一、正常異步任務
為了演示方便,異步任務的執行采用 thread.sleep(long)
模擬,現在假設用戶請求以下接口 :
http://localhost:7000/demo/getuserwithnothing.json
異步任務接口定義如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
/** * 測試沒有發生任何異常的異步任務 */ @requestmapping (value = "getuserwithnothing.json" , method = requestmethod.get) public webasynctask<string> getuserwithnothing() { // 打印處理線程名 system.err.println( "the main thread name is " + thread.currentthread().getname()); // 此處模擬開啟一個異步任務,超時時間為10s webasynctask<string> task1 = new webasynctask<string>( 10 * 1000l, () -> { system.err.println( "the first thread name is " + thread.currentthread().getname()); // 任務處理時間5s,不超時 thread.sleep( 5 * 1000l); return "任務1順利執行成功!任何異常都沒有拋出!" ; }); // 任務執行完成時調用該方法 task1.oncompletion(() -> { system.err.println( "任務1執行完成啦!" ); }); system.err.println( "task1繼續處理其他事情!" ); return task1; } |
控制臺打印如下:
the main thread name is http-nio-7000-exec-1
task1繼續處理其他事情!
the first thread name is mvcasync1
任務1執行完成啦!
瀏覽器結果如下:

二、拋異常異步任務
接口調用 : http://localhost:7000/demo/getuserwitherror.json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
/** * 測試發生error的異步任務 * @return */ @requestmapping (value = "getuserwitherror.json" , method = requestmethod.get) public webasynctask<string> getuserwitherror() { system.err.println( "the main thread name is " + thread.currentthread().getname()); // 此處模擬開啟一個異步任務 webasynctask<string> task3 = new webasynctask<string>( 10 * 1000l, () -> { system.err.println( "the second thread name is " + thread.currentthread().getname()); // 此處拋出異常 int num = 9 / 0 ; system.err.println(num); return "" ; }); // 發生異常時調用該方法 task3.onerror(() -> { system.err.println( "====================================" + thread.currentthread().getname() + "==============================" ); system.err.println( "任務3發生error啦!" ); return "" ; }); // 任務執行完成時調用該方法 task3.oncompletion(() -> { system.err.println( "任務3執行完成啦!" ); }); system.err.println( "task3繼續處理其他事情!" ); return task3; } |
控制臺輸出如下:
the main thread name is http-nio-7000-exec-1
task3繼續處理其他事情!
the second thread name is mvcasync1
2018-06-15 09:40:13.538 error 9168 --- [nio-7000-exec-2] o.a.c.c.c.[.[.[.[dispatcherservlet] : servlet.service() for servlet [dispatcherservlet] threw exceptionjava.lang.arithmeticexception: / by zero
at com.example.demo.controller.getuserinfocontroller.lambda$5(getuserinfocontroller.java:93) ~[classes/:na]
at org.springframework.web.context.request.async.webasyncmanager.lambda$startcallableprocessing$4(webasyncmanager.java:317) ~[spring-web-5.0.6.release.jar:5.0.6.release]
at java.util.concurrent.executors$runnableadapter.call(executors.java:511) ~[na:1.8.0_161]
at java.util.concurrent.futuretask.run(futuretask.java:266) ~[na:1.8.0_161]
at java.lang.thread.run(thread.java:748) [na:1.8.0_161]2018-06-15 09:40:13.539 error 9168 --- [nio-7000-exec-2] o.a.c.c.c.[.[.[.[dispatcherservlet] : servlet.service() for servlet [dispatcherservlet] in context with path [/demo] threw exception [request processing failed; nested exception is java.lang.arithmeticexception: / by zero] with root cause
java.lang.arithmeticexception: / by zero
at com.example.demo.controller.getuserinfocontroller.lambda$5(getuserinfocontroller.java:93) ~[classes/:na]
at org.springframework.web.context.request.async.webasyncmanager.lambda$startcallableprocessing$4(webasyncmanager.java:317) ~[spring-web-5.0.6.release.jar:5.0.6.release]
at java.util.concurrent.executors$runnableadapter.call(executors.java:511) ~[na:1.8.0_161]
at java.util.concurrent.futuretask.run(futuretask.java:266) ~[na:1.8.0_161]
at java.lang.thread.run(thread.java:748) [na:1.8.0_161]====================================http-nio-7000-exec-2==============================
任務3發生error啦!
任務3執行完成啦!
當然你也可以對上面做一些異常處理,不至于在用戶看來顯得不友好,關于異常處理,可以查看我的另一篇文章 spring boot/spring 統一錯誤處理方案的使用
瀏覽器輸出結果:

三、超時異步任務
接口調用 : http://localhost:7000/demo/getuserwithtimeout.json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
/** * 測試發生任務超時的異步任務 * @return */ @requestmapping (value = "getuserwithtimeout.json" , method = requestmethod.get) public webasynctask<string> getuserwithtimeout() { system.err.println( "the main thread name is " + thread.currentthread().getname()); // 此處模擬開啟一個異步任務,超時10s webasynctask<string> task2 = new webasynctask<string>( 10 * 1000l, () -> { system.err.println( "the second thread name is " + thread.currentthread().getname()); thread.sleep( 20 * 1000l); return "任務2執行超時!" ; }); // 任務超時調用該方法 task2.ontimeout(() -> { system.err.println( "====================================" + thread.currentthread().getname() + "==============================" ); return "任務2發生超時啦!" ; }); // 任務執行完成時調用該方法 task2.oncompletion(() -> { system.err.println( "任務2執行完成啦!" ); }); system.err.println( "task2繼續處理其他事情!" ); return task2; } |
控制臺執行結果:
the main thread name is http-nio-7000-exec-4
task2繼續處理其他事情!
the second thread name is mvcasync2
====================================http-nio-7000-exec-5==============================
任務2執行完成啦!
瀏覽器執行結果:

四、線程池異步任務
上面的三種情況中的異步任務默認不是采用線程池機制進行管理的,也就是說,一個請求進來,雖然釋放了處理線程,但是系統依舊會為每個請求創建一個異步任務線程,也就是上面我們看到的 mvcasync
開頭的異步任務線程,那這樣不行啊,開銷特別大呀!所以我們可以采用線程池進行管理,直接在 webasynctask
類構造器傳入一個 threadpooltaskexecutor
對象實例即可。
下面我們先看看,當對上面第一種情況執行并發請求時會出現什么情況(此處模擬對 http://localhost:7000/demo/getuserwithnothing.json
進行并發調用):
控制臺輸出如下:
the first thread name is mvcasync57
the first thread name is mvcasync58
the first thread name is mvcasync59
the first thread name is mvcasync60
the first thread name is mvcasync61
the first thread name is mvcasync62
the first thread name is mvcasync63
the first thread name is mvcasync64
the first thread name is mvcasync65
the first thread name is mvcasync66
the first thread name is mvcasync67
the first thread name is mvcasync68
the first thread name is mvcasync69
the first thread name is mvcasync70
the first thread name is mvcasync71
the first thread name is mvcasync72
the first thread name is mvcasync73
the first thread name is mvcasync74
the first thread name is mvcasync76
the first thread name is mvcasync75
the first thread name is mvcasync77
the first thread name is mvcasync78
the first thread name is mvcasync79
the first thread name is mvcasync80
由于沒有加入線程池,所以100個請求將開啟100個異步任務線程,開銷特別大,不推薦。
下面是采用線程池的實現 :
調用接口 : http://localhost:7000/demo/getuserwithexecutor.json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
/** * 測試線程池 * @return */ @requestmapping (value = "getuserwithexecutor.json" , method = requestmethod.get) public webasynctask<string> getuserwithexecutor() { system.err.println( "the main thread name is " + thread.currentthread().getname()); // 此處模擬開啟一個異步任務,此處傳入一個線程池 webasynctask<string> task1 = new webasynctask<string>( 10 * 1000l, executor, () -> { system.err.println( "the first thread name is " + thread.currentthread().getname()); thread.sleep(5000l); return "任務4順利執行成功!任何異常都沒有拋出!" ; }); // 任務執行完成時調用該方法 task1.oncompletion(() -> { system.err.println( "任務4執行完成啦!" ); }); system.err.println( "task4繼續處理其他事情!" ); return task1; } |
線程池定義如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@configuration public class myexecutor { @bean public static threadpooltaskexecutor getexecutor() { threadpooltaskexecutor taskexecutor = new threadpooltaskexecutor(); taskexecutor.setcorepoolsize( 30 ); taskexecutor.setmaxpoolsize( 30 ); taskexecutor.setqueuecapacity( 50 ); taskexecutor.setthreadnameprefix( "huang" ); // 異步任務線程名以 huang 為前綴 return taskexecutor; } } |
對上面進行并發測試,可以得出下面結果 :
本文示例代碼地址: https://github.com/smallercoder/webasynctask
采用線程池可以節約服務器資源,優化服務器處理能力,要記得常用喲!謝謝閱讀!覺得對你有幫助,請給個start哦!
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://juejin.im/post/5b230edde51d4558bc58bc14