简体   繁体   English

并行化 REST 调用的最佳方法是什么?

[英]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.

相关问题 在JSP中并行化调用的最佳方法是什么? - What's the best way to parallelize calls in JSP? 并行化 Pulsar 消费者工作负载的最佳方式是什么? - What is the best way to parallelize Pulsar consumer workload? 记录REST方法调用的最佳方法是什么? - What is the best way to do logging for REST method call? 在Cucumber中存储REST API响应的最佳方法是什么 - What's the best way to store REST API responses in Cucumber 为Java Rest API初始化数据的最佳方法是什么? - What's the best way to init data for Java Rest API? 并行化此Java代码的最佳方法 - Best way to parallelize this Java code 并行化数千次下载的最佳方式 - Best way to parallelize thousands of downloads 用一种方式对列表中的某些项目进行排序,而另一种方式进行排序的最佳方法是什么? - What's the best way to sort some items in a list in one way, and the rest, another way? 通过 REST 调用将多达 100 万条记录导出到 excel 工作表的最佳方法是什么? - What is the best way to export upto 1 million records into excel sheet via REST call? 使用REST功能编写AuthenticationFilter的最佳方法是什么? - What is the best way to write a AuthenticationFilter with REST features?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM