我正在尝试在Spring reactive中聚合5个服务调用的结果。每个服务调用都会进行一个外部API调用,并得到一个结果。
示例:
Mono<A> = serviceCall1(...);
Mono<B> = serviceCall2(...);
Mono<C> = serviceCall3(...);
Mono<D> = serviceCall4(...);
Mono<E> = serviceCall5(...);我需要做的是并行执行所有这些调用,将结果聚合到一个单声道中。但是,如果任何调用失败,我应该仍然能够确保所有调用完成。有些调用可能会失败,有些可能会成功。
我该怎么做呢?
发布于 2020-08-05 23:50:56
所有你需要使用的是Mono中的压缩操作。只需确保在上面的每个Monos中都有onErrorResume回退。然后,当接收到现有Monos的所有值时,Mono.zip将运行。
发布于 2021-12-28 19:07:30
您可以压缩Mono的方法,其中可以传递多个Mono。请参考以下示例:
Mono<A> monoA = serviceCall1();
Mono<B> monoB = serviceCall2();
Mono<C> monoC = serviceCall3();
Mono.zip(monoA, monoB, monoC).flatMap(tuple -> {
//here tuple will contain combined response of 3 Mono's which you have passed
//in zip method
// tuple.getT1() will give you response of MonoA (first call)
// tuple.getT2() will give you response of MonoB (second call)
// tuple.getT3() will give you response of MonoC (third call)
// infact you can create new object with response of above 3.
});参考:https://www.tabnine.com/code/java/methods/reactor.core.publisher.Mono/zip
https://stackoverflow.com/questions/55233247
复制相似问题