這期內(nèi)容當中小編將會給大家?guī)碛嘘P(guān)SpringBoot中怎么異步調(diào)用方法并接收返回值,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
章丘網(wǎng)站建設公司成都創(chuàng)新互聯(lián)公司,章丘網(wǎng)站設計制作,有大型網(wǎng)站制作公司豐富經(jīng)驗。已為章丘上千余家提供企業(yè)網(wǎng)站建設服務。企業(yè)網(wǎng)站搭建\外貿(mào)網(wǎng)站建設要多少錢,請找那個售后服務好的章丘做網(wǎng)站的公司定做!
步驟1:配置線程池,添加@Configuration和@EnableAsync注解
@Configuration@EnableAsyncpublic 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()); // 等待所有任務都完成再繼續(xù)銷毀其他的Bean executor.setWaitForTasksToCompleteOnShutdown(true); // 線程池中任務的等待時間,如果超過這個時候還沒有銷毀就強制銷毀,以確保應用最后能夠被關(guān)閉,而不是阻塞住 executor.setAwaitTerminationSeconds(60); executor.initialize(); return executor; } }
步驟2:定義方法A,方法B,方法C,方法D
@Servicepublic 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; }}
上述就是小編為大家分享的SpringBoot中怎么異步調(diào)用方法并接收返回值了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關(guān)知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
本文標題:SpringBoot中怎么異步調(diào)用方法并接收返回值
文章路徑:http://bm7419.com/article38/geiesp.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供商城網(wǎng)站、App設計、、網(wǎng)站收錄、網(wǎng)站設計、云服務器
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)