Spring Boot異步調(diào)用@Async過(guò)程詳解
在實(shí)際開(kāi)發(fā)中,有時(shí)候?yàn)榱思皶r(shí)處理請(qǐng)求和進(jìn)行響應(yīng),我們可能會(huì)多任務(wù)同時(shí)執(zhí)行,或者先處理主任務(wù),也就是異步調(diào)用,異步調(diào)用的實(shí)現(xiàn)有很多,例如多線程、定時(shí)任務(wù)、消息隊(duì)列等,
我們來(lái)講講@Async異步方法調(diào)用。
一、@Async使用演示
@Async是Spring內(nèi)置注解,用來(lái)處理異步任務(wù),在SpringBoot中同樣適用,且在SpringBoot項(xiàng)目中,除了boot本身的starter外,不需要額外引入依賴。
而要使用@Async,需要在啟動(dòng)類上加上@EnableAsync主動(dòng)聲明來(lái)開(kāi)啟異步方法。
@EnableAsync
@SpringBootApplication
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
}
現(xiàn)假設(shè)有3個(gè)任務(wù)需要去處理,分別對(duì)應(yīng)AsyncTask類的taskOne、taskTwo、taskThree方法,這里做了線程的sleep來(lái)模擬實(shí)際運(yùn)行。
@Slf4j
@Component
public class AsyncTask {
private Random random = new Random();
public void taskOne() throws InterruptedException {
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
log.info("任務(wù)一執(zhí)行完成耗時(shí){}秒", (end - start)/1000f);
}
public void taskTwo() throws InterruptedException {
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
log.info("任務(wù)二執(zhí)行完成耗時(shí){}秒", (end - start)/1000f);
}
public void taskThree() throws InterruptedException {
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
log.info("任務(wù)三執(zhí)行完成耗時(shí){}秒", (end - start)/1000f);
}
}
然后編寫(xiě)測(cè)試類,由于@Async注解需要再Spring容器啟動(dòng)后才能生效,所以這里講測(cè)試類放到了SpringBoot的test包下,使用了SpringBootTest。
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootApplication.class)
public class AsyncTaskTest {
@Autowired
private AsyncTask asyncTask;
@Test
public void doAsyncTasks(){
try {
long start = System.currentTimeMillis();
asyncTask.taskOne();
asyncTask.taskTwo();
asyncTask.taskThree();
Thread.sleep(5000);
long end = System.currentTimeMillis();
log.info("主程序執(zhí)行完成耗時(shí){}秒", (end - start)/1000f);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
運(yùn)行測(cè)試方法,可以在控制臺(tái)看到任務(wù)一二三按順序執(zhí)行,最后主程序完成,這和我們的預(yù)期一樣,因?yàn)槲覀儧](méi)有任何額外的處理,他們就是普通的方法,按編碼順序依次執(zhí)行。

而如果要使任務(wù)并發(fā)執(zhí)行,我們只需要在任務(wù)方法上使用@Async注解即可,需要注意的是@Async所修飾的方法不要定義為static類型,這樣異步調(diào)用不會(huì)生效。
@Slf4j
@Component
public class AsyncTask {
private Random random = new Random();
//@Async所修飾的函數(shù)不要定義為static類型,這樣異步調(diào)用不會(huì)生效
@Async
public void taskOne() throws InterruptedException {
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
log.info("任務(wù)一執(zhí)行完成耗時(shí){}秒", (end - start)/1000f);
}
@Async
public void taskTwo() throws InterruptedException {
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
log.info("任務(wù)二執(zhí)行完成耗時(shí){}秒", (end - start)/1000f);
}
@Async
public void taskThree() throws InterruptedException {
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
log.info("任務(wù)三執(zhí)行完成耗時(shí){}秒", (end - start)/1000f);
}
}
然后我們?cè)谶\(yùn)行測(cè)試類,這個(gè)時(shí)候輸出可能就五花八門(mén)了,任意任務(wù)都可能先執(zhí)行完成,也有可能有的方法因?yàn)橹鞒绦蜿P(guān)閉而沒(méi)有輸出。

二、Future獲取異步執(zhí)行結(jié)果
上面演示了@Async,但是有時(shí)候除了需要任務(wù)并發(fā)調(diào)度外,我們還需要獲取任務(wù)的返回值,且在多任務(wù)都執(zhí)行完成后再結(jié)束主任務(wù),這個(gè)時(shí)候又該怎么處理呢?
在多線程里通過(guò)Callable和Future可以獲取返回值,這里也是類似的,我們使用Future返回方法的執(zhí)行結(jié)果,AsyncResult是Future的一個(gè)實(shí)現(xiàn)類。
@Slf4j
@Component
public class FutureTask {
private Random random = new Random();
//@Async所修飾的函數(shù)不要定義為static類型,這樣異步調(diào)用不會(huì)生效
@Async
public Future<String> taskOne() throws InterruptedException {
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
log.info("任務(wù)一執(zhí)行完成耗時(shí){}秒", (end - start)/1000f);
return new AsyncResult <>("任務(wù)一Ok");
}
@Async
public Future<String> taskTwo() throws InterruptedException {
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
log.info("任務(wù)二執(zhí)行完成耗時(shí){}秒", (end - start)/1000f);
return new AsyncResult <>("任務(wù)二OK");
}
@Async
public Future<String> taskThree() throws InterruptedException {
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
log.info("任務(wù)三執(zhí)行完成耗時(shí){}秒", (end - start)/1000f);
return new AsyncResult <>("任務(wù)三Ok");
}
}
在AsyncResult中:
- isDone()方法可以用于判斷異步方法是否執(zhí)行完成,若任務(wù)完成,則返回true
- get()方法可用于獲取任務(wù)執(zhí)行后返回的結(jié)果
- cancel(boolean mayInterruptIfRunning)可用于取消任務(wù),參數(shù)mayInterruptIfRunning表示是否允許取消正在執(zhí)行卻沒(méi)有執(zhí)行完畢的任務(wù),如果設(shè)置true,則表示可以取消正在執(zhí)行過(guò)程中的任務(wù)
- isCancelled()方法表示任務(wù)是否被取消成功,如果在任務(wù)正常完成前被取消成功,則返回 true
- get(long timeout, TimeUnit unit)用來(lái)獲取執(zhí)行結(jié)果,如果在指定時(shí)間內(nèi),還沒(méi)獲取到結(jié)果,就直接返回null
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootApplication.class)
public class AsyncTaskTest {
@Autowired
private FutureTask futureTask;
@Test
public void doFutureTasks(){
try {
long start = System.currentTimeMillis();
Future <String> future1 = futureTask.taskOne();
Future <String> future2 = futureTask.taskTwo();
Future <String> future3 = futureTask.taskThree();
//3個(gè)任務(wù)執(zhí)行完成之后再執(zhí)行主程序
do {
Thread.sleep(100);
} while (future1.isDone() && future2.isDone() && future3.isDone());
log.info("獲取異步方法的返回值:{}", future1.get());
Thread.sleep(5000);
long end = System.currentTimeMillis();
log.info("主程序執(zhí)行完成耗時(shí){}秒", (end - start)/1000f);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
運(yùn)行測(cè)試類,我們可以看到任務(wù)一二三異步執(zhí)行了,主任務(wù)最后執(zhí)行完成,而且可以獲取到任務(wù)的返回信息。

源碼地址:https://github.com/imyanger/springboot-project/tree/master/p23-springboot-async
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Spring Boot優(yōu)雅地處理404異常問(wèn)題
這篇文章主要介紹了Spring Boot優(yōu)雅地處理404異常問(wèn)題,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-11-11
淺談Java中向上造型向下造型和接口回調(diào)中的問(wèn)題
這篇文章主要介紹了淺談Java中向上造型向下造型和接口回調(diào)中的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-08-08
Java日常練習(xí)題,每天進(jìn)步一點(diǎn)點(diǎn)(61)
下面小編就為大家?guī)?lái)一篇Java基礎(chǔ)的幾道練習(xí)題(分享)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧,希望可以幫到你2021-08-08
Springboot中的@ComponentScan注解使用解析
這篇文章主要介紹了Springboot中的@ComponentScan注解使用解析,@ComponentScan用于類或接口上主要是指定掃描路徑,spring會(huì)把指定路徑下帶有指定注解的類注冊(cè)到IOC容器中,需要的朋友可以參考下2024-01-01
java開(kāi)發(fā)建造者模式驗(yàn)證實(shí)例詳解
這篇文章主要為大家介紹了java開(kāi)發(fā)中建造者模式的驗(yàn)證實(shí)例詳解,文中附含詳細(xì)示例代碼,有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-10-10
Java計(jì)時(shí)器StopWatch實(shí)現(xiàn)方法代碼實(shí)例
這篇文章主要介紹了Java計(jì)時(shí)器StopWatch實(shí)現(xiàn)方法代碼實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-07-07

