java - 在 Spring Webflux 中组合多个单声道

标签 java spring-boot spring-webflux project-reactor

我是 webflux 的新手,我正在尝试使用 Flux 执行多个单声道。但我认为我做错了..这是执行多个 Mono 并将其收集到列表中的最佳方法吗?

这是我的代码:

    mainService.getAllBranch()
            .flatMapMany(branchesList -> {
                List<Branch> branchesList2 = (List<Branch>) branchesList.getData();
                List<Mono<Transaction>> trxMonoList= new ArrayList<>();

                branchesList2.stream().forEach(branch -> {
                    trxMonoList.add(mainService.getAllTrxByBranchId(branch.branchId));
                });
                return Flux.concat(trxMonoList); // <--- is there any other way than using concat?
            })
            .collectList()
            .flatMap(resultList -> combineAllList());
    interface MainService{
            Mono<RespBody> getAllBranch();
            Mono<RespBody> getAllTrxByBranchId(String branchId); //will return executed url ex: http://trx.com/{branchId}
    }

到目前为止我用上面的代码我可以这样解释:

  1. 获取所有分支
  2. 遍历所有 branchesList2 并将其添加到 trxMonoList
  3. return Flux.concat,这是我不确定方法是否正确的地方。但它的工作
  4. 合并所有列表

我只是想知道这是不是在我的上下文中使用 Flux 的正确方法?还是有更好的方法来实现我正在尝试做的事情?

最佳答案

您需要将代码重构为响应式代码。

 mainService.getAllBranch()
        .flatMapMany(branchesList -> Flux.fromIterable(branchesList.getData())) (1)
        .flatMap(branch -> mainService.getAllTrxByBranchId(branch.branchId))    (2)
        .collectList()
        .flatMap(resultList -> combineAllList());

1) 从 List 中创建 Flux 分支;

2) 遍历每个元素并调用服务。

您不应该在 Reactor 中使用 Stream API,因为它具有相同的方法,但具有针对多线程的适配和优化。

关于java - 在 Spring Webflux 中组合多个单声道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61487090/

相关文章:

java - 如何将多个 View 合并到一张位图中

运行maven package命令时java spring boot jar文件错误

java - 使用 WebFlux 对特定映射进行并行 GET 请求

java - 使用 Spring WebClient 重复过滤响应

java - Spring RequestContextHolder 和 WebTestClient

java - if 语句应该打印字符串值

java - 将字符串格式化为 java8 ZonedDateTime

java - 获取创建文件的日期/时间

java - Kafka AdminClient 似乎启动了两次

java - 使用maven-spring-boot-plugin时将类路径添加到SpringBoot命令行启动