springboot實現(xiàn)異步任務(wù)
本文實例為大家分享了springboot實現(xiàn)異步任務(wù)的具體代碼,供大家參考,具體內(nèi)容如下
1.什么異步任務(wù)同步:一定要等任務(wù)執(zhí)行完了,得到結(jié)果,才執(zhí)行下一個任務(wù)。異步:不等任務(wù)執(zhí)行完,直接執(zhí)行下一個任務(wù)。
2.異步任務(wù)使用場景在許多網(wǎng)站中,都會有發(fā)送郵件驗證郵箱功能,執(zhí)行該任務(wù)時,需要較長的時間,此時為了更好的用戶體驗,前端可以先返回完成的信息,后臺去執(zhí)行任務(wù)。
3.異步任務(wù)的實現(xiàn)步驟首先模擬一個網(wǎng)站跳轉(zhuǎn)的過程,假設(shè)某一個線程執(zhí)行任務(wù)時需要5秒,結(jié)束以后才會進行下一步操作,我們令線程休眠五秒,然后通過controller進行頁面跳轉(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則可以使用更簡便的方式來實現(xiàn)異步任務(wù)調(diào)度。我們只需要在Service層需要多線程處理的方法上加上@Async注解。
然后在主啟動類上加上**@EnableAsync**注解來開啟異步注解功能即可執(zhí)行異步任務(wù)調(diào)度,此時執(zhí)行可立即跳轉(zhuǎn)然后再執(zhí)行hello方法控制臺來輸出“數(shù)據(jù)正在傳送”。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. python time.strptime格式化實例詳解2. Java SiteMesh新手學(xué)習(xí)教程代碼案例3. axios和ajax的區(qū)別點總結(jié)4. PHP 工程師面試的四個環(huán)節(jié)5. XML解析錯誤:未組織好 的解決辦法6. 解決ajax的delete、put方法接收不到參數(shù)的問題方法7. Vue router安裝及使用方法解析8. 將properties文件的配置設(shè)置為整個Web應(yīng)用的全局變量實現(xiàn)方法9. Android webview注入JS代碼 修改網(wǎng)頁內(nèi)容操作10. Spring下Filter過濾器配置全局異常處理的詳細步驟
