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ù)使用場景在許多網(wǎng)站中,都會(huì)有發(fā)送郵件驗(yàn)證郵箱功能,執(zhí)行該任務(wù)時(shí),需要較長的時(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則可以使用更簡便的方式來實(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ù)正在傳送”。
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. docker容器調(diào)用yum報(bào)錯(cuò)的解決辦法2. Docker容器如何更新打包并上傳到阿里云3. idea重置默認(rèn)配置的方法步驟4. IntelliJ IDEA安裝插件的方法步驟5. idea設(shè)置自動(dòng)導(dǎo)入依賴的方法步驟6. idea修改背景顏色樣式的方法7. idea給項(xiàng)目打war包的方法步驟8. idea刪除項(xiàng)目的操作方法9. IntelliJ IDEA導(dǎo)入項(xiàng)目的方法10. vue 添加和編輯用同一個(gè)表單,el-form表單提交后清空表單數(shù)據(jù)操作
