欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot異步調(diào)用方法并接收返回值

 更新時間:2019年09月24日 10:33:51   作者:myCat、  
這篇文章主要為大家詳細介紹了SpringBoot異步調(diào)用方法并接收返回值,具有一定的參考價值,感興趣的小伙伴們可以參考一下

項目中肯定會遇到異步調(diào)用其他方法的場景,比如有個計算過程,需要計算很多個指標的值,但是每個指標計算的效率快慢不同,如果采用同步執(zhí)行的方式,運行這一個過程的時間是計算所有指標的時間之和。比如:

方法A:計算指標x,指標y,指標z的值,其中計算指標x需要1s,計算指標y需要2s,指標z需要3s。最終執(zhí)行完方法A就是5s。

現(xiàn)在用異步的方式優(yōu)化一下

方法A異步調(diào)用方法B,方法C,方法D,方法B,方法C,方法D分別計算指標x,指標y,指標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)文章

最新評論