在多个线程中调用多个 rest/soap 服务并等待它们的响应



我必须从一个方法调用三个方法。这三种方法依次调用各种 REST 或 SOAP 服务。 我想使这三个方法的处理是异步的,即其余调用和 soap 调用是并行进行的。另外,我希望主线程等待所有这些线程完成,然后对线程接收的数据进行一些处理。 实现这一目标的最佳方法是什么? 我想我可以研究以下方法——

  • fork join (Java 7(
  • 并行流
  • 执行程序服务(在这种情况下使用它是否明智?

还有其他方法吗? 以上哪种方式最适合我的方案?

遗嘱执行人服务 + 可组合期货

List<CompletableFuture<SomeResponse>> futures = new ArrayList<>();
//assign futures to executor
futures.add(CompletableFuture.supplyAsync(() -> client.perform(request), executor));
...
//create combined future
CompletableFuture combinedFuture = CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]));
//wait for all features to execute or timeout
combinedFuture.get(50, TimeUnit.SECONDS);
//go through results
for (CompletableFuture<SomeResponse> future : futures){
...
}

最新更新