springboot實現異步任務
本文實例為大家分享了springboot實現異步任務的具體代碼,供大家參考,具體內容如下
1.什么異步任務同步:一定要等任務執行完了,得到結果,才執行下一個任務。異步:不等任務執行完,直接執行下一個任務。
2.異步任務使用場景在許多網站中,都會有發送郵件驗證郵箱功能,執行該任務時,需要較長的時間,此時為了更好的用戶體驗,前端可以先返回完成的信息,后臺去執行任務。
3.異步任務的實現步驟首先模擬一個網站跳轉的過程,假設某一個線程執行任務時需要5秒,結束以后才會進行下一步操作,我們令線程休眠五秒,然后通過controller進行頁面跳轉
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('數據正在傳送!'); }}
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'; }}總結:
SpringBoot則可以使用更簡便的方式來實現異步任務調度。我們只需要在Service層需要多線程處理的方法上加上@Async注解。
然后在主啟動類上加上**@EnableAsync**注解來開啟異步注解功能即可執行異步任務調度,此時執行可立即跳轉然后再執行hello方法控制臺來輸出“數據正在傳送”。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: