Springboot任務之異步任務的使用詳解
更新時間:2021年06月07日 16:31:12 作者:Z && Y
今天學習了一個新技能SpringBoot實現(xiàn)異步任務,所以特地整理了本篇文章,文中有非常詳細的介紹及代碼示例,需要的朋友可以參考下
一、SpringBoot--異步任務
1.1 什么是同步和異步
- 同步是阻塞模式,異步是非阻塞模式。
- 同步就是指一個進程在執(zhí)行某個請求的時候,若該請求需要一段時間才能返回信息,那么這個進程將會—直等待下去,知道收到返回信息才繼續(xù)執(zhí)行下去
- 異步是指進程不需要一直等下去,而是繼續(xù)執(zhí)行下面的操作,不管其他進程的狀態(tài)。當有消息返回式系統(tǒng)會通知進程進行處理,這樣可以提高執(zhí)行的效率。
1.2 Java模擬一個異步請求(線程休眠)
AsyncService.java
package com.tian.asyncdemo.service; import org.springframework.stereotype.Service; @Service public class AsyncService { public void hello() { try { System.out.println("數(shù)據正在處理"); Thread.sleep(3000); System.out.println("數(shù)據處理完成"); } catch (InterruptedException e) { e.printStackTrace(); } } }
AsyncController.java
package com.tian.asyncdemo.controller; import com.tian.asyncdemo.service.AsyncService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * ClassName: AsyncController * Description: * * @author Administrator * @date 2021/6/6 19:48 */ @RestController public class AsyncController { @Autowired AsyncService asyncService; @RequestMapping("/hello") public String hello() { asyncService.hello(); return "OK"; } }
運行結果:
1.3 使用異步
在Service的方法中使用@Async說這是一個異步方法,并在主入口上使用@EnableAsync開啟異步支持
AsyncService.java
@Service public class AsyncService { @Async public void hello() { try { System.out.println("數(shù)據正在處理"); Thread.sleep(3000); System.out.println("數(shù)據處理完成"); } catch (InterruptedException e) { e.printStackTrace(); } } }
主入口上使用@EnableAsync開啟異步支持
再次測試:
到此這篇關于Springboot任務之異步任務的使用詳解的文章就介紹到這了,更多相關SpringBoot異步任務內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Springboot配置security basic path無效解決方案
這篇文章主要介紹了Springboot配置security basic path無效解決方案,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-09-09ArrayList和JSONArray邊遍歷邊刪除到底該如何做
這篇文章主要介紹了ArrayList和JSONArray邊遍歷邊刪除到底該如何做,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-12-12金三銀四復工高頻面試題java算法LeetCode396旋轉函數(shù)
這篇文章主要為大家介紹了金三銀四復工高頻面試題之java算法題解LeetCode396旋轉函數(shù),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-02-02淺談Java讀寫注冊表的方式Preferences與jRegistry
這篇文章主要介紹了淺談Java讀寫注冊表的方式Preferences與jRegistry,分享了相關代碼示例,小編覺得還是挺不錯的,具有一定借鑒價值,需要的朋友可以參考下2018-02-02