[英]Combine multiple mono in Spring Webflux
I'm new with webflux and I'm trying to execute multiple monos with Flux
.我是 webflux 的新手,我正在尝试使用
Flux
执行多个单声道。 But i think i'm doing it wrong.. is this the best approach to execute multiple Mono
and collect it to list?但我认为我做错了..这是执行多个
Mono
并将其收集到列表的最佳方法吗?
Here is my code:这是我的代码:
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}
}
so far my with above code i can explain it like this:到目前为止,我用上面的代码可以这样解释:
branchesList2
and add it to trxMonoList
branchesList2
并将其添加到trxMonoList
Flux.concat
, this is where i'm not sure is this the right way or not.Flux.concat
,这是我不确定这是否正确的地方。 but it's workingI'm just confuse is this the proper way to use Flux
in my context?我只是困惑这是在我的上下文中使用
Flux
的正确方法吗? or is there any better way to achieve with what i'm trying to do?或者有没有更好的方法来实现我想要做的事情?
You need to refactor a little bit your code to reactive.您需要将代码重构为反应式。
mainService.getAllBranch()
.flatMapMany(branchesList -> Flux.fromIterable(branchesList.getData())) (1)
.flatMap(branch -> mainService.getAllTrxByBranchId(branch.branchId)) (2)
.collectList()
.flatMap(resultList -> combineAllList());
1) Create Flux of branches from List; 1)从列表中创建分支通量;
2) Iterate through the each element and call a service. 2)遍历每个元素并调用服务。
You shouldn't use Stream API in Reactor because it has the same methods but with adaptaptions and optimisations for multythreading.您不应该在 Reactor 中使用 Stream API,因为它具有相同的方法,但对多线程进行了适应和优化。
The real problem here is that you shouldn't be hitting a Mono
multiple times within a Flux
.这里真正的问题是你不应该在
Flux
内多次击中Mono
。 That will give you problems.那会给你带来麻烦。 If you are designing the API you should fix that to do what you want in a correct reactive manner.
如果您正在设计 API,您应该修复它以正确的反应方式做您想做的事情。
interface MainService{
Flux<Branch> getAllBranch();
Flux<Transaction> getAllTrxByBranchId(Flux<String> branchIds);
}
Then your code becomes simpler and the reactive framework will work properly.然后你的代码变得更简单,反应式框架将正常工作。
mainService.getAllTrxByBranchId(mainService.getAllBranch().map(Branch::getId));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.