问题描述
我是反应式编程的新手.我看到可以压缩两个单声道来生成结果:
I am new in reactive programming. I saw that two monos could be zipped to generate a result:
Mono<Info> info = Mono.just(id).map(this::getInfo).subscribeOn(Schedulers.parallel());
Mono<List<Detail>> detail= Mono.just(petitionRequest).map(this.service::getDetails)
.subscribeOn(Schedulers.parallel());
Flux<Generated> flux = Flux.zip(detail, info, (p, c) -> {
Generated o = Generated.builder().info(c).detail(p).build();
return o;
});
据我所知,这将两次调用并发,并生成当我调用 flux.blockFirst()
As I have understood this paralelizes the two call and generate the object Generated when I call to flux.blockFirst()
如何将另一个单声道合并到现有的两个单声道以生成结果?Flux.zip仅接受两个单声道.
How can I merge another mono to the existing two ones to generate a result? Flux.zip only accepts two monos.
谢谢.
推荐答案
首先,由于要压缩Monos,因此使用 zip 运算符,而不是Flux.
First of all, since you are zipping Monos, it would make sense to use zip operator from Mono instead of Flux.
它具有多个重载版本,可以接受任意数量的Monos.
It has multiple overloaded versions which can accept any number of Monos.
此外,如果 this.service :: getDetails
和 this :: getInfo
阻止IO操作(HTTP请求,数据库调用等),则应使用Elastic调度程序而不是并行程序,后者用于CPU密集型操作.
Also, if this.service::getDetails
and this::getInfo
are blocking IO operations (HTTP request, database call, etc.) then you should use elastic Scheduler instead of the parallel one, the latter is intended for CPU intensive operations.
示例代码:
Mono<Info> info = Mono.just(id)
.map(this::getInfo)
.subscribeOn(Schedulers.elastic());
Mono<List<Detail>> detail= Mono.just(petitionRequest)
.map(this.service::getDetails)
.subscribeOn(Schedulers.elastic());
Mono<Description> description = Mono.just(id)
.map(this::callService)
.subscribe(Schedulers.elastic());
Mono.zip(info, detail, description)
.map(this::map);
private Generated map(Tuple3<Info, List<Detail>, Description> tuple3)
{
Info info = tuple3.getT1();
List<Detail> details = tuple3.getT2();
Description description = tuple3.getT3();
// build output here
}
这篇关于从3个不同的单声道创建实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!