【问题标题】:Spring webflux - multi MonoSpring webflux - 多单声道
【发布时间】:2018-11-17 02:19:09
【问题描述】:

我不知道或问这个问题,除了这里,如果不是我道歉的地方。

我目前正在开发一个使用 spring webflux 的应用程序,但我在使用 Mono 和 Flux 时遇到了问题。

这里我有一个 REST 请求,它带有一个简单的 bean,其中包含属性,包括一个列表。迭代此列表以使用返回 Mono (findOne) 的响应式 mongo 调用。 但我认为我没有找到正确的方法:

@PostMapping
@RequestMapping("/check")
public Mono<ContactCheckResponse> check(@RequestBody List<ContactCheckRequest> list) {
    final ContactCheckResponse response = new ContactCheckResponse();
    response.setRsnCode("00");
    response.setRspnCode("0000");
    LOG.debug("o--> person - check {} items", list.size());

    final List<ContactCheckResponse.Contact> contacts = new ArrayList<>();
    response.setContacts(contacts);

    return Mono.fromCallable(() -> {
        list.stream().forEach( c -> {
            Boolean exists = contactRespository.findOneByThumbprint(c.getIdentifiant()).block() != null;
            ContactCheckResponse.Contact responseContact = new ContactCheckResponse.Contact();
            responseContact.setExist(exists);
            responseContact.setIdentifiant(c.getIdentifiant());
            responseContact.setRsnCode("00");
            responseContact.setRspnCode("0000");
            response.getContacts().add(responseContact);
        });
        return response;
    });
}

在“反应性”的想法中,我似乎并不认为必须制作一个块的事实,但我没有找到其他方法。

有人可以帮我找到完成这项任务的最佳方法吗?

谢谢

【问题讨论】:

    标签: spring-boot reactive-programming spring-webflux


    【解决方案1】:

    类似的东西:

    return Flux.fromIterable(list)
      .flatMap(c -> contactRespository.findOneByThumbprint(c.getIdentifiant())
                      .map(r -> r != null)
                      .map(exists -> {
                             ContactCheckResponse.Contact responseContact = new ContactCheckResponse.Contact();
                             ...
                             return responseContact;
                          })
              )
     .reduce(response, (r,c) -> {
                                   response.getContacts().add(responseContact);
                                   return response;
             });       
    

    从列表中创建一个Flux,为每个条目创建一个联系人并将所有内容减少为Mono

    【讨论】:

    • .reduce(response, (r,c) -> { r.getContacts().add(responseContact); return r; });
    • @Pierre-YvesNicolas 不客气。是的,return r; 更可取。
    猜你喜欢
    • 2020-08-12
    • 2020-10-22
    • 2018-12-05
    • 2019-10-06
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 2020-04-13
    相关资源
    最近更新 更多