我知道可以链接 Mono,例如...
I know it is possible to chain Mono's, for ex,...
Mono<String> resultAMono = loadA(); Mono<String> resultBMono = resultA.flatMap(resultA -> loadB());这将链接并且 resultBMono 将在 resultAMono 返回时运行....
This will chain and resultBMono will run when resultAMono returns....
所以我的问题是,是否可以并行启动 2 个 Mono,并且当两个返回都继续使用另一个 Mono 时?
So my question is, is it possible to start 2 Mono's in parallel and when both returns continue with another Mono?
我认为它看起来像这样......
I think it will look something like this...
Mono<String> resultAMono = loadA(); Mono<String> resuktBMono = loadB(); Mono<Tuple2<Stirng, String> tupleMono = Mono.zip(resultAMono, resultBMono);但我不知道这会并行运行,或者我可以做些什么来并行运行...
but I have no idea this will run in Parallel or what can I do this to run in parallel...
感谢回答....
推荐答案2个语义,1个让它们并行运行的方法
我在下面介绍的两个选项都需要一些额外的调整才能使 A 和 B Mono 并行运行:即,每个 Mono 应该使用 subscribeOn(Scheduler) 从它们合并的地方脱离公共线程.
The two options I present below both need some additional tuning to make A and B Mono run in parallel: namely, each Mono should use subscribeOn(Scheduler) to get out of the common thread from where they're merged.
如果你只关心A和B的完成
使用 when 来监听 A 和 B 完成,then 继续使用完全不同的 Mono:
Use when to listen for A and B completion and then to continue with a completely different Mono:
Mono.when(monoAwithSubscribeOn, monoBwithSubscribeOn) .then(Mono.just("A and B finished, I don't know their value"));如果您关心 A 和 B 值
根据您想要对结果做什么,使用 zip + map/flatMap.
Use zip + map/flatMap depending on what you want to do with the result.
Mono.zip(monoAwithSubscribeOn, monoBwithSubscribeOn) .map(tuple2 -> new Foo(tuple2.getT1(), tuple2.getT2(), "bar");或
Mono.zip(monoAwithSubscribeOn, monoBwithSubscribeOn) .flatMap(tuple2 -> fetchMoreDataAsMono(tuple2.getT1(), tuple2.getT2()));then 会忽略前面的数据,所以在它之前使用 zip 没有多大意义.
then will ignore the previous data, so it wouldn't make much sense to use zip before it.
此外,如果 A 或 B 之一为空,zip 将导致 空 Mono!使用 switchIfEmpty/defaultIfEmpty 来防止这种情况.
also, zip will result in an empty Mono if one of A or B is empty! Use switchIfEmpty/defaultIfEmpty to protect against that case.
更多推荐
是否可以并行启动 Mono 并汇总结果
发布评论