开发者社区> 问答> 正文

Projectreactor:查询的并行执行和结果的并置

晚上好。我正在研究反应式编程,遇到了以下问题。

我正在对数据库运行两个并行查询,想要合并结果并将其返回

    @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
}

相反,我得到了一个空的答复。显然,这是由于mono zip引起的,但是在保持查询并行性的同时,我还可以如何合并结果呢?

我的实体:

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

我该如何解决这种情况?

问题来源:Stack Overflow

展开
收起
montos 2020-03-25 22:39:43 1024 0
1 条回答
写回答
取消 提交回答
  • Zip/ZipWith需要元素来产生其输出。如果可以为空,则可以使用以下方法设置一些默认值。

    • defaultIfEmpty(new Comment()) 要么
    • switchIfEmpty(Mono.fromSupplier(() -> 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;
                     });
    

    回答来源:Stack Overflow

    2020-03-25 22:40:28
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载

相关实验场景

更多