[英]What's the best way to parallelize a REST call?
I'm working on some java code, which processes multiple REST calls我正在处理一些处理多个 REST 调用的 Java 代码
call1()
call2()
call3()
...
I want to parallelize these calls, but perform my main code synchronously.我想并行化这些调用,但同步执行我的主要代码。 I made a POC with lamba and a parallel stream:
我用lamba和并行流制作了一个POC:
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.
我还检查了使用来自 Jersey 客户端的异步调用,但这需要更多的代码更改。
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:您可以使用
CompletableFuture
提交任务,然后等待它们完成:
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.
发生这种情况时,该方法将返回。
You may need to control the thread pool for your async tasks.您可能需要控制异步任务的线程池。 This is an example using a 10-thread pool:
这是一个使用 10 线程池的示例:
ExecutorService es = Executors.newFixedThreadPool(10);
list.stream()
.map(r -> CompletableFuture.runAsync(r, es))
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.