Springboot任務(wù)之異步任務(wù)的使用詳解
一、SpringBoot--異步任務(wù)
1.1 什么是同步和異步
- 同步是阻塞模式,異步是非阻塞模式。
- 同步就是指一個(gè)進(jìn)程在執(zhí)行某個(gè)請(qǐng)求的時(shí)候,若該請(qǐng)求需要一段時(shí)間才能返回信息,那么這個(gè)進(jìn)程將會(huì)—直等待下去,知道收到返回信息才繼續(xù)執(zhí)行下去
- 異步是指進(jìn)程不需要一直等下去,而是繼續(xù)執(zhí)行下面的操作,不管其他進(jìn)程的狀態(tài)。當(dāng)有消息返回式系統(tǒng)會(huì)通知進(jìn)程進(jìn)行處理,這樣可以提高執(zhí)行的效率。
1.2 Java模擬一個(gè)異步請(qǐng)求(線程休眠)

AsyncService.java
package com.tian.asyncdemo.service;
import org.springframework.stereotype.Service;
@Service
public class AsyncService {
public void hello() {
try {
System.out.println("數(shù)據(jù)正在處理");
Thread.sleep(3000);
System.out.println("數(shù)據(jù)處理完成");
} 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";
}
}
運(yùn)行結(jié)果:

1.3 使用異步
在Service的方法中使用@Async說這是一個(gè)異步方法,并在主入口上使用@EnableAsync開啟異步支持

AsyncService.java
@Service
public class AsyncService {
@Async
public void hello() {
try {
System.out.println("數(shù)據(jù)正在處理");
Thread.sleep(3000);
System.out.println("數(shù)據(jù)處理完成");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
主入口上使用@EnableAsync開啟異步支持

再次測(cè)試:

到此這篇關(guān)于Springboot任務(wù)之異步任務(wù)的使用詳解的文章就介紹到這了,更多相關(guān)SpringBoot異步任務(wù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java實(shí)現(xiàn)的Windows資源管理器實(shí)例
這篇文章主要介紹了Java實(shí)現(xiàn)的Windows資源管理器,實(shí)例分析了基于java實(shí)現(xiàn)windows資源管理器的相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-07-07
springboot 運(yùn)行 jar 包讀取外部配置文件的問題
這篇文章主要介紹了springboot 運(yùn)行 jar 包讀取外部配置文件,本文主要描述linux系統(tǒng)執(zhí)行jar包讀取jar包同級(jí)目錄的外部配置文件,主要分為兩種方法,每種方法通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2021-07-07
Spring中propagation的7種事務(wù)配置及說明
這篇文章主要介紹了Spring中propagation的7種事務(wù)配置及說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06
Spring @Retryable注解輕松搞定循環(huán)重試功能
spring系列的spring-retry是另一個(gè)實(shí)用程序模塊,可以幫助我們以標(biāo)準(zhǔn)方式處理任何特定操作的重試。在spring-retry中,所有配置都是基于簡(jiǎn)單注釋的。本文主要介紹了Spring@Retryable注解如何輕松搞定循環(huán)重試功能,有需要的朋友可以參考一下2023-04-04
Spring Boot集成ElasticSearch實(shí)現(xiàn)搜索引擎的示例
這篇文章主要介紹了Spring Boot集成ElasticSearch實(shí)現(xiàn)搜索引擎的示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-11-11
在spring?boot3中使用native?image的最新方法
這篇文章主要介紹了在spring?boot3中使用native?image?,今天我們用具體的例子來給大家演示一下如何正確的將spring boot3的應(yīng)用編譯成為native image,需要的朋友可以參考下2023-01-01

