SpringBoot異步調(diào)用方法并接收返回值
項目中肯定會遇到異步調(diào)用其他方法的場景,比如有個計算過程,需要計算很多個指標(biāo)的值,但是每個指標(biāo)計算的效率快慢不同,如果采用同步執(zhí)行的方式,運行這一個過程的時間是計算所有指標(biāo)的時間之和。比如:
方法A:計算指標(biāo)x,指標(biāo)y,指標(biāo)z的值,其中計算指標(biāo)x需要1s,計算指標(biāo)y需要2s,指標(biāo)z需要3s。最終執(zhí)行完方法A就是5s。
現(xiàn)在用異步的方式優(yōu)化一下
方法A異步調(diào)用方法B,方法C,方法D,方法B,方法C,方法D分別計算指標(biāo)x,指標(biāo)y,指標(biāo)z的值,那么最終執(zhí)行完方法A的時間則是3s。
步驟1:配置線程池,添加@Configuration和@EnableAsync注解
@Configuration
@EnableAsync
public class ExecutorConfig {
/**
* 線程池
*
* @return
*/
@Bean(name = "asyncExecutor")
public Executor asyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(15);
executor.setQueueCapacity(25);
executor.setKeepAliveSeconds(200);
executor.setThreadNamePrefix("async-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
// 等待所有任務(wù)都完成再繼續(xù)銷毀其他的Bean
executor.setWaitForTasksToCompleteOnShutdown(true);
// 線程池中任務(wù)的等待時間,如果超過這個時候還沒有銷毀就強制銷毀,以確保應(yīng)用最后能夠被關(guān)閉,而不是阻塞住
executor.setAwaitTerminationSeconds(60);
executor.initialize();
return executor;
}
}
步驟2:定義方法A,方法B,方法C,方法D
@Service
public class AsyncService {
@Async("asyncExecutor")
public Future<Integer> methodB(){
try{
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
return new AsyncResult<>(1);
}
@Async("asyncExecutor")
public Future<Integer> methodC(){
try{
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
return new AsyncResult<>(2);
}
@Async("asyncExecutor")
public Future<Integer> methodD(){
try{
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
return new AsyncResult<>(3);
}
}
@GetMapping("test")
public Integer methodA() throws Exception{
long start = System.currentTimeMillis();
Future<Integer> future1 = asyncService.methodB();
Future<Integer> future2 = asyncService.methodC();
Future<Integer> future3 = asyncService.methodD();
Integer x = future1.get();
Integer y = future2.get();
Integer z = future3.get();
long end = System.currentTimeMillis();
System.out.println("耗時:" + (end - start));
return x + y +z;
}
}
結(jié)果:


關(guān)于Futura類的詳解請移步:了解JAVA Future類
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
詳解Struts2中json 相互引用死循環(huán)解決辦法
本篇文章主要介紹詳解Struts2中json 相互引用死循環(huán)解決辦法,具有一定的參考價值,有興趣的可以了解一下。2017-01-01
Spring Data Jpa如何實現(xiàn)批量插入或更新
文章總結(jié):本文分享了四種Spring Data JPA批量插入或更新的方法,包括BatchConsumer、QueryParameterBuilder、KeyValue和SqlUtil,旨在為開發(fā)者提供實用的參考2024-12-12
idea在工具欄中顯示快速創(chuàng)建包和類的圖標(biāo)的詳細(xì)步驟
點擊需要創(chuàng)建包或者類的位置,在點擊對用的圖標(biāo)就可以快速創(chuàng)建類或者包了,下面小編給大家介紹idea在工具欄中顯示快速創(chuàng)建包和類的圖標(biāo)的詳細(xì)步驟,感興趣的朋友一起看看吧2024-02-02
Intellij Idea中批量導(dǎo)入第三方j(luò)ar包的全過程
引入jar包一般都是針對小的java項目,這篇文章主要給大家介紹了關(guān)于Intellij Idea中批量導(dǎo)入第三方j(luò)ar包的相關(guān)資料,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2021-10-10
基于SpringMVC實現(xiàn)網(wǎng)頁登錄攔截
SpringMVC的處理器攔截器類似于Servlet開發(fā)中的過濾器Filter,用于對處理器進行預(yù)處理和后處理。因此,本文將為大家介紹如何通過SpringMVC實現(xiàn)網(wǎng)頁登錄攔截功能,需要的小伙伴可以了解一下2021-12-12

