一、springboot中異步請求的使用
1、異步請求與同步請求
特點:
可以先釋放容器分配給請求的線程與相關資源,減輕系統負擔,釋放了容器所分配線程的請求,其響應將被延后,可以在耗時處理完成(例如長時間的運算)時再對客戶端進行響應。一句話:增加了服務器對客戶端請求的吞吐量(實際生產上我們用的比較少,如果并發請求量很大的情況下,我們會通過nginx把請求負載到集群服務的各個節點上來分攤請求壓力,當然還可以通過消息隊列來做請求的緩沖)。
2、異步請求的實現
方式一:servlet方式實現異步請求
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
@requestmapping (value = "/email/servletreq" , method = get) public void servletreq (httpservletrequest request, httpservletresponse response) { asynccontext asynccontext = request.startasync(); //設置監聽器:可設置其開始、完成、異常、超時等事件的回調處理 asynccontext.addlistener( new asynclistener() { @override public void ontimeout(asyncevent event) throws ioexception { system.out.println( "超時了..." ); //做一些超時后的相關操作... } @override public void onstartasync(asyncevent event) throws ioexception { system.out.println( "線程開始" ); } @override public void onerror(asyncevent event) throws ioexception { system.out.println( "發生錯誤:" +event.getthrowable()); } @override public void oncomplete(asyncevent event) throws ioexception { system.out.println( "執行完成" ); //這里可以做一些清理資源的操作... } }); //設置超時時間 asynccontext.settimeout( 20000 ); asynccontext.start( new runnable() { @override public void run() { try { thread.sleep( 10000 ); system.out.println( "內部線程:" + thread.currentthread().getname()); asynccontext.getresponse().setcharacterencoding( "utf-8" ); asynccontext.getresponse().setcontenttype( "text/html;charset=utf-8" ); asynccontext.getresponse().getwriter().println( "這是異步的請求返回" ); } catch (exception e) { system.out.println( "異常:" +e); } //異步請求完成通知 //此時整個請求才完成 asynccontext.complete(); } }); //此時之類 request的線程連接已經釋放了 system.out.println( "主線程:" + thread.currentthread().getname()); } |
方式二:使用很簡單,直接返回的參數包裹一層callable即可,可以繼承webmvcconfigureradapter類來設置默認線程池和超時處理
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
|
@requestmapping (value = "/email/callablereq" , method = get) @responsebody public callable<string> callablereq () { system.out.println( "外部線程:" + thread.currentthread().getname()); return new callable<string>() { @override public string call() throws exception { thread.sleep( 10000 ); system.out.println( "內部線程:" + thread.currentthread().getname()); return "callable!" ; } }; } @configuration public class requestasyncpoolconfig extends webmvcconfigureradapter { @resource private threadpooltaskexecutor mythreadpooltaskexecutor; @override public void configureasyncsupport( final asyncsupportconfigurer configurer) { //處理 callable超時 configurer.setdefaulttimeout( 60 * 1000 ); configurer.settaskexecutor(mythreadpooltaskexecutor); configurer.registercallableinterceptors(timeoutcallableprocessinginterceptor()); } @bean public timeoutcallableprocessinginterceptor timeoutcallableprocessinginterceptor() { return new timeoutcallableprocessinginterceptor(); } } |
方式三:和方式二差不多,在callable外包一層,給webasynctask設置一個超時回調,即可實現超時處理
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
|
@requestmapping (value = "/email/webasyncreq" , method = get) @responsebody public webasynctask<string> webasyncreq () { system.out.println( "外部線程:" + thread.currentthread().getname()); callable<string> result = () -> { system.out.println( "內部線程開始:" + thread.currentthread().getname()); try { timeunit.seconds.sleep( 4 ); } catch (exception e) { // todo: handle exception } logger.info( "副線程返回" ); system.out.println( "內部線程返回:" + thread.currentthread().getname()); return "success" ; }; webasynctask<string> wat = new webasynctask<string>(3000l, result); wat.ontimeout( new callable<string>() { @override public string call() throws exception { // todo auto-generated method stub return "超時" ; } }); return wat; } |
方式四:deferredresult可以處理一些相對復雜一些的業務邏輯,最主要還是可以在另一個線程里面進行業務處理及返回,即可在兩個完全不相干的線程間的通信。
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
33
34
35
|
@requestmapping (value = "/email/deferredresultreq" , method = get) @responsebody public deferredresult<string> deferredresultreq () { system.out.println( "外部線程:" + thread.currentthread().getname()); //設置超時時間 deferredresult<string> result = new deferredresult<string>( 60 *1000l); //處理超時事件 采用委托機制 result.ontimeout( new runnable() { @override public void run() { system.out.println( "deferredresult超時" ); result.setresult( "超時了!" ); } }); result.oncompletion( new runnable() { @override public void run() { //完成后 system.out.println( "調用完成" ); } }); mythreadpooltaskexecutor.execute( new runnable() { @override public void run() { //處理業務邏輯 system.out.println( "內部線程:" + thread.currentthread().getname()); //返回結果 result.setresult( "deferredresult!!" ); } }); return result; } |
二、springboot中異步調用的使用
1、介紹
異步請求的處理。除了異步請求,一般上我們用的比較多的應該是異步調用。通常在開發過程中,會遇到一個方法是和實際業務無關的,沒有緊密性的。比如記錄日志信息等業務。這個時候正常就是啟一個新線程去做一些業務處理,讓主線程異步的執行其他業務。
2、使用方式(基于spring下)
- 需要在啟動類加入@enableasync使異步調用@async注解生效
- 在需要異步執行的方法上加入此注解即可@async(“threadpool”),threadpool為自定義線程池
- 代碼略。。。就倆標簽,自己試一把就可以了
3、注意事項
- 在默認情況下,未設置taskexecutor時,默認是使用simpleasynctaskexecutor這個線程池,但此線程不是真正意義上的線程池,因為線程不重用,每次調用都會創建一個新的線程。可通過控制臺日志輸出可以看出,每次輸出線程名都是遞增的。所以最好我們來自定義一個線程池。
- 調用的異步方法,不能為同一個類的方法(包括同一個類的內部類),簡單來說,因為spring在啟動掃描時會為其創建一個代理類,而同類調用時,還是調用本身的代理類的,所以和平常調用是一樣的。其他的注解如@cache等也是一樣的道理,說白了,就是spring的代理機制造成的。所以在開發中,最好把異步服務單獨抽出一個類來管理。下面會重點講述。。
4、什么情況下會導致@async異步方法會失效?
調用同一個類下注有@async異步方法:在spring中像@async和@transactional、cache等注解本質使用的是動態代理,其實spring容器在初始化的時候spring容器會將含有aop注解的類對象“替換”為代理對象(簡單這么理解),那么注解失效的原因就很明顯了,就是因為調用方法的是對象本身而不是代理對象,因為沒有經過spring容器,那么解決方法也會沿著這個思路來解決。
- 調用的是靜態(static )方法
- 調用(private)私有化方法
5、解決4中問題1的方式(其它2,3兩個問題自己注意下就可以了)
將要異步執行的方法單獨抽取成一個類,原理就是當你把執行異步的方法單獨抽取成一個類的時候,這個類肯定是被spring管理的,其他spring組件需要調用的時候肯定會注入進去,這時候實際上注入進去的就是代理類了。
其實我們的注入對象都是從spring容器中給當前spring組件進行成員變量的賦值,由于某些類使用了aop注解,那么實際上在spring容器中實際存在的是它的代理對象。那么我們就可以通過上下文獲取自己的代理對象調用異步方法。
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
|
@controller @requestmapping ( "/app" ) public class emailcontroller { //獲取applicationcontext對象方式有多種,這種最簡單,其它的大家自行了解一下 @autowired private applicationcontext applicationcontext; @requestmapping (value = "/email/asynccall" , method = get) @responsebody public map<string, object> asynccall () { map<string, object> resmap = new hashmap<string, object>(); try { //這樣調用同類下的異步方法是不起作用的 //this.testasynctask(); //通過上下文獲取自己的代理對象調用異步方法 emailcontroller emailcontroller = (emailcontroller)applicationcontext.getbean(emailcontroller. class ); emailcontroller.testasynctask(); resmap.put( "code" , 200 ); } catch (exception e) { resmap.put( "code" , 400 ); logger.error( "error!" ,e); } return resmap; } //注意一定是public,且是非static方法 @async public void testasynctask() throws interruptedexception { thread.sleep( 10000 ); system.out.println( "異步任務執行完成!" ); } } |
開啟cglib代理,手動獲取spring代理類,從而調用同類下的異步方法。
首先,在啟動類上加上@enableaspectjautoproxy(exposeproxy = true)注解。
代碼實現,如下:
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
|
@service @transactional (value = "transactionmanager" , readonly = false , propagation = propagation.required, rollbackfor = throwable. class ) public class emailservice { @autowired private applicationcontext applicationcontext; @async public void testsynctask() throws interruptedexception { thread.sleep( 10000 ); system.out.println( "異步任務執行完成!" ); } public void asynccalltwo() throws interruptedexception { //this.testsynctask(); // emailservice emailservice = (emailservice)applicationcontext.getbean(emailservice.class); // emailservice.testsynctask(); boolean isaop = aoputils.isaopproxy(emailcontroller. class ); //是否是代理對象; boolean iscglib = aoputils.iscglibproxy(emailcontroller. class ); //是否是cglib方式的代理對象; boolean isjdk = aoputils.isjdkdynamicproxy(emailcontroller. class ); //是否是jdk動態代理方式的代理對象; //以下才是重點!!! emailservice emailservice = (emailservice)applicationcontext.getbean(emailservice. class ); emailservice proxy = (emailservice) aopcontext.currentproxy(); system.out.println(emailservice == proxy ? true : false ); proxy.testsynctask(); system.out.println( "end!!!" ); } } |
三、異步請求與異步調用的區別
- 兩者的使用場景不同,異步請求用來解決并發請求對服務器造成的壓力,從而提高對請求的吞吐量;而異步調用是用來做一些非主線流程且不需要實時計算和響應的任務,比如同步日志到kafka中做日志分析等。
- 異步請求是會一直等待response相應的,需要返回結果給客戶端的;而異步調用我們往往會馬上返回給客戶端響應,完成這次整個的請求,至于異步調用的任務后臺自己慢慢跑就行,客戶端不會關心。
四、總結
- 異步請求和異步調用的使用到這里基本就差不多了,有問題還希望大家多多指出。
- 這邊文章提到了動態代理,而spring中aop的實現原理就是動態代理,后續會對動態代理做詳細解讀,還望多多支持哈~
總結
以上所述是小編給大家介紹的springboot中異步請求和異步調用問題,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:https://blog.csdn.net/tiantuo6513/article/details/89061460