【问题标题】:Projectreactor: the parallel execution of queries and concatenating the resultsProjectreactor:并行执行查询并连接结果
【发布时间】:2020-06-26 08:49:46
【问题描述】:

晚上好。 我在学习响应式编程,遇到了以下问题。

我正在对数据库运行两个并行查询,并希望合并结果并将它们返回

    @GetMapping
    public Mono<User> get(@RequestParam("id") String id, @RequestParam("cId") String cId) {
        Mono<User> userMono = Mono.fromCallable(() -> userServ.get(id))
                .flatMap(userMono1 -> userMono1)
                .subscribeOn(Schedulers.boundedElastic());

        Mono<Comment> ger = Mono.fromCallable(() -> commentServ.ger(cId))
                .flatMap(commentMono -> commentMono)
                .subscribeOn(Schedulers.boundedElastic());


        return Mono.zip(userMono, ger)
                .map(pair -> {
                    User t1 = pair.getT1();
                    t1.setComment(pair.getT2());
                    return t1;
                });

但是重点是注释可能是空的,然后我期望返回这样一个结构的json

{
    "id": "5e6cbf395214a42f51b57121",
    "name": "Bob",
    "surname": null,
    "comment": null
}

相反,我得到一个空的响应。显然这是由于单声道压缩,但我还能如何组合结果,同时保持查询并行性

我的实体:

@Document
@AllArgsConstructor
@NoArgsConstructor
@Data
public class Comment {
    @Id
    String id;
    String userId;
    String comment;
}

@Document
@AllArgsConstructor
@NoArgsConstructor
@Data
public class User {
    @Id
    private String id;
    private String name;
    private String surname;
    private Comment comment;
}

我该如何解决这种情况?

【问题讨论】:

    标签: java spring multithreading spring-webflux project-reactor


    【解决方案1】:

    Zip/ZipWith 需要元素来产生它们的输出。如果它可以是空的,你可以使用下面的方法来设置一些默认值。

    • defaultIfEmpty(new Comment())
    • switchIfEmpty(Mono.fromSupplier(() -&gt; new Comment())

    如果您不想使用new Comment() 并将null 设置为评论对象,我们可以尝试这种方式。

            userMono
                    .zipWith(commentMono.defaultIfEmpty(new Comment()))
                    .map(pair -> {
                        User user = pair.getT1();
                        Comment comment = pair.getT2();
                        if(Objects.nonNull(comment.getUserId()))
                           user.setComment(comment);
                        return user;
                     });
    

    【讨论】:

    • 我认为这也是Optional的主要案例
    猜你喜欢
    • 1970-01-01
    • 2017-09-10
    • 1970-01-01
    • 2019-02-05
    • 1970-01-01
    • 1970-01-01
    • 2013-04-25
    • 2013-02-07
    • 2020-10-08
    相关资源
    最近更新 更多