【问题标题】:Create entity from 3 different mono从 3 个不同的单声道创建实体
【发布时间】:2019-07-22 08:08:07
【问题描述】:

我是响应式编程的新手。我看到可以压缩两个单声道以生成结果:

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;
        });

据我了解,这将两个调用并行化并生成对象 Generated when I call to flux.blockFirst()

如何将另一个单声道与现有的两个单声道合并以生成结果? Flux.zip 只接受两个单声道。

提前致谢。

【问题讨论】:

    标签: java spring project-reactor


    【解决方案1】:

    首先,由于您正在压缩 Monos,因此使用 Mono 中的 zip 运算符而不是 Flux 是有意义的。

    它有多个重载版本,可以接受任意数量的 Monos。

    另外,如果 this.service::getDetailsthis::getInfo 正在阻塞 IO 操作(HTTP 请求、数据库调用等),那么您应该使用弹性调度器而不是并行调度器,后者适用于 CPU 密集型操作。

    示例代码:

        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
        }
    

    【讨论】:

    • 感谢 Yossarian,所以 Flux 仅在您想压缩 Mono 和 Flux 时使用?
    • 如果您的发布者可以生产多个项目(例如:多个 Flux),那么使用 Flux 中的 zip 可能是有意义的。如果您正在处理 Monos,则值得保持简单并使用 Mono.zip。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-13
    • 1970-01-01
    • 2020-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多