问题描述
我正在处理一些Java代码,该代码可以处理多个REST调用
I'm working on some java code, which processes multiple REST calls
call1()
call2()
call3()
...
我想并行化这些调用,但是要同步执行我的主代码.我用lamba和并行流制作了POC:
I want to parallelize these calls, but perform my main code synchronously.I made a POC with lamba and a parallel stream:
List<Runnable> list = new ArrayList();
list.add(() -> {call1()});
list.add(() -> {call2()});
list.add(() -> {call3()});
list.add(...);
list.parallelStream()
.forEach(Runnable::run);
您还有其他解决方案吗?我还检查了使用泽西客户端的异步调用,但是这需要更多代码更改.
Do you have another solution?I also checked to use async calls from Jersey client instead, but this would need more code changes.
推荐答案
您所需要的只是异步运行您的呼叫.您可以使用 CompletableFuture
s提交任务,然后等待它们完成:
All you're looking for is to run your calls asynchronously. You can use CompletableFuture
s to submit the task, and then wait for them to complete:
list.stream() //you don't really need a parallel stream
.map(CompletableFuture::runAsync)
.collect(Collectors.toList()) //make sure all tasks are submitted
.stream()
.forEach(CompletableFuture::join);
这将提交所有任务(以异步方式运行),然后等待它们中的每一个完成运行.发生这种情况时,该方法将返回.
This will submit all tasks (to run asynchronously), and then wait for each of them to finish running. When that happens, the method will return.
您可能需要控制异步任务的线程池.这是一个使用10线程池的示例:
You may need to control the thread pool for your async tasks. This is an example using a 10-thread pool:
ExecutorService es = Executors.newFixedThreadPool(10);
list.stream()
.map(r -> CompletableFuture.runAsync(r, es))
...
这篇关于并行化REST调用的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!