java - 使用 Project Reactor 并行调用其余 Web 服务?

标签 java spring spring-boot project-reactor

我想知道如何对 REST 或 Web 服务进行多个并行调用,然后加入响应并在调用 @RestController 的响应中发送它。

类似于使用 ComparableFuture 构建的以下代码,但使用 Reactor(Flux, Mono)。

CompletableFuture<Company> companyCompletableFuture = CompletableFuture.supplyAsync(() -> {
     return  Company.find.where().eq("id", id).findUnique();  
});

CompletableFuture<List<Domain>> domainsCompletableFuture = CompletableFuture.supplyAsync(() -> {
     return Domain.find.where().eq("company_id", id).findList();
});

// wait for all the data
CompletableFuture allDoneFuture = CompletableFuture.allOf(companyCompletableFuture, domainsCompletableFuture);

allDoneFuture.get(); // wait for all done
company = companyCompletableFuture.get();
domain = domainsCompletableFuture.get()

最佳答案

您可以从 callable 创建两个 Mono,然后压缩它们。如果您想并行执行可调用,您还需要显式添加 subscribeOn(Schedulers.parallel()) 到每个 Mono:

Mono<Integer> mono1 = Mono.fromCallable(() -> {
    System.out.println(Thread.currentThread().getName());
    return 123;
}).subscribeOn(Schedulers.parallel());

Mono<Integer> mono2 = Mono.fromCallable(() -> {
    System.out.println(Thread.currentThread().getName());
    return 321;
}).subscribeOn(Schedulers.parallel());

Tuple2<Integer, Integer> result = mono1.zipWith(mono2).block();

System.out.println(result.getT1());
System.out.println(result.getT2());

结果将是这样的:

parallel-1
parallel-2
123
321

关于java - 使用 Project Reactor 并行调用其余 Web 服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48785968/

相关文章:

java - 从切换到分支/标签历史记录中删除网址

java - 解析文档时如何将文档中字符串的一部分替换为另一个字符串

java - 如何在 jhipster 创建的应用程序中更改身份验证类型

spring - 结合 springBoot 和 elasticsearch 2.x

spring-boot - 从groovy迁移到Kotlin Gradle脚本后,单元测试中出现NullPointerException

java - 在 play 2.0 中加载 initial-data.yml 时出现问题

java - JPA:从数据库获取数据而不是持久性上下文

java - Jboss/野蝇: programmatically add classes to Hibernate

java - 错误 404 Spring-MVC

Spring Boot 设置 SSL 连接报错