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)的過(guò)程,假設(shè)某一個(gè)線程執(zhí)行任務(wù)時(shí)需要5秒,結(jié)束以后才會(huì)進(jìn)行下一步操作,我們令線程休眠五秒,然后通過(guò)controller進(jìn)行頁(yè)面跳轉(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)便的方式來(lái)實(shí)現(xiàn)異步任務(wù)調(diào)度。我們只需要在Service層需要多線程處理的方法上加上@Async注解。
然后在主啟動(dòng)類上加上**@EnableAsync**注解來(lái)開(kāi)啟異步注解功能即可執(zhí)行異步任務(wù)調(diào)度,此時(shí)執(zhí)行可立即跳轉(zhuǎn)然后再執(zhí)行hello方法控制臺(tái)來(lái)輸出“數(shù)據(jù)正在傳送”。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 網(wǎng)頁(yè)中img圖片使用css實(shí)現(xiàn)等比例自動(dòng)縮放不變形(代碼已測(cè)試)2. vue組件庫(kù)的在線主題編輯器的實(shí)現(xiàn)思路3. idea設(shè)置自動(dòng)導(dǎo)入依賴的方法步驟4. Python安裝并操作redis實(shí)現(xiàn)流程詳解5. AspNetCore&MassTransit Courier實(shí)現(xiàn)分布式事務(wù)的詳細(xì)過(guò)程6. 部署vue+Springboot前后端分離項(xiàng)目的步驟實(shí)現(xiàn)7. ajax post下載flask文件流以及中文文件名問(wèn)題8. Python常用擴(kuò)展插件使用教程解析9. html清除浮動(dòng)的6種方法示例10. ASP腳本組件實(shí)現(xiàn)服務(wù)器重啟
