springboot實(shí)現(xiàn)異步任務(wù)
本文實(shí)例為大家分享了springboot實(shí)現(xiàn)異步任務(wù)的具體代碼,供大家參考,具體內(nèi)容如下
1.什么異步任務(wù)同步:一定要等任務(wù)執(zhí)行完了,得到結(jié)果,才執(zhí)行下一個(gè)任務(wù)。異步:不等任務(wù)執(zhí)行完,直接執(zhí)行下一個(gè)任務(wù)。
2.異步任務(wù)使用場(chǎng)景在許多網(wǎng)站中,都會(huì)有發(fā)送郵件驗(yàn)證郵箱功能,執(zhí)行該任務(wù)時(shí),需要較長(zhǎng)的時(shí)間,此時(shí)為了更好的用戶體驗(yàn),前端可以先返回完成的信息,后臺(tái)去執(zhí)行任務(wù)。
3.異步任務(wù)的實(shí)現(xiàn)步驟首先模擬一個(gè)網(wǎng)站跳轉(zhuǎn)的過程,假設(shè)某一個(gè)線程執(zhí)行任務(wù)時(shí)需要5秒,結(jié)束以后才會(huì)進(jìn)行下一步操作,我們令線程休眠五秒,然后通過controller進(jìn)行頁面跳轉(zhuǎn)
service
package com.kuang.service;import org.springframework.scheduling.annotation.Async;import org.springframework.stereotype.Service;@Servicepublic class AsyncService { @Async public void hello(){try { Thread.sleep(5000);} catch (InterruptedException e) { e.printStackTrace();}System.out.println('數(shù)據(jù)正在傳送!'); }}
controller
package com.kuang.controller;import com.kuang.service.AsyncService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class AsyncController { @Autowired AsyncService asyncService; @RequestMapping('/hello') public String hello(){asyncService.hello();return 'OK'; }}總結(jié):
SpringBoot則可以使用更簡(jiǎn)便的方式來實(shí)現(xiàn)異步任務(wù)調(diào)度。我們只需要在Service層需要多線程處理的方法上加上@Async注解。
然后在主啟動(dòng)類上加上**@EnableAsync**注解來開啟異步注解功能即可執(zhí)行異步任務(wù)調(diào)度,此時(shí)執(zhí)行可立即跳轉(zhuǎn)然后再執(zhí)行hello方法控制臺(tái)來輸出“數(shù)據(jù)正在傳送”。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. python實(shí)現(xiàn)讀取類別頻數(shù)數(shù)據(jù)畫水平條形圖案例2. python中PyQuery庫(kù)用法分享3. python操作數(shù)據(jù)庫(kù)獲取結(jié)果之fetchone和fetchall的區(qū)別說明4. php5.6不能擴(kuò)展redis.so的解決方法5. Ajax實(shí)現(xiàn)頁面無刷新留言效果6. CSS3實(shí)現(xiàn)動(dòng)態(tài)翻牌效果 仿百度貼吧3D翻牌一次動(dòng)畫特效7. ASP.NET MVC前臺(tái)動(dòng)態(tài)添加文本框并在后臺(tái)使用FormCollection接收值8. PHP獲取時(shí)間戳等相關(guān)函數(shù)匯總9. AJAX實(shí)現(xiàn)數(shù)據(jù)的增刪改查操作詳解【java后臺(tái)】10. php使用正則驗(yàn)證密碼字段的復(fù)雜強(qiáng)度原理詳細(xì)講解 原創(chuàng)
