我是 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}
}
到目前为止我用上面的代码我可以这样解释:
- 获取所有分支
- 遍历所有
branchesList2
并将其添加到trxMonoList
- return
Flux.concat
,这是我不确定方法是否正确的地方。但它的工作 - 合并所有列表
我只是想知道这是不是在我的上下文中使用 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/