英文:
Invoke 2 APIs parallely - what is the recommended approach? reactive vs executor?
问题
有一个使用情况,需要并行调用两个服务,然后将结果合并并返回给调用者。(基于Java,Spring Boot)实现这一目标有哪些不同的方法?线程处理(Java Executor)还是响应式编程?
只有在从服务A和服务B获得响应后,才能确定“服务E”的响应。
调用者 -> 暴露的服务(服务E) -> 服务A,服务B
英文:
Have a use case where two services need to be invoked in parallel and then combine the result and return to the caller. (Java, Spring boot based) What are the different approaches possible to achieve this? Threading (Java Executor) or Reactive programming?
The response of 'Service E' can be decided only after getting the response from Service A and Service B.
Caller -> Exposed Service (Service E) -> Service A, Service B
答案1
得分: 0
我不知道什么是最佳方法,但我以前使用过并且对我有效的解决方案是使用可比较的 Futures。以下是一个示例:
CompletableFuture<ResponseA> futureA
= CompletableFuture.supplyAsync(() -> serviceA.getResponse());
CompletableFuture<ResponseB> futureB
= CompletableFuture.supplyAsync(() -> serviceB.getResponse());
CompletableFuture<Void> combinedFuture
= CompletableFuture.allOf(futureA, futureB);
// ...
combinedFuture.get();
这段代码将并行执行两个服务调用,并在等待两个调用都完成后才退出 get()
。在获取后,您可以从 future 变量中提取响应。
英文:
I don't know what is the best approach but a solution I've used int he past and has worked for me is using comparable futures. Here is an example:
CompletableFuture<ResponseA> futureA
= CompletableFuture.supplyAsync(() -> serviceA.getResponse());
CompletableFuture<ResponseB> futureB
= CompletableFuture.supplyAsync(() -> serviceB.getResponse());
CompletableFuture<Void> combinedFuture
= CompletableFuture.allOf(futureA, futureB);
// ...
combinedFuture.get();
This piece of code will execute both services calls in parallel and it will wait until both calls are finished to exit the get(). After the get you can extract the response from the future variables.
专注分享java语言的经验与见解,让所有开发者获益!
评论