简体   繁体   English

同时执行两个查询(反应式)

[英]Perform two queries at the same time (reactive)

I know it is asynchronous and therefore the values I want to save will be null (I checked).我知道它是异步的,因此我要保存的值将是 null(我检查过)。 How can I fix this so that everything is saved correctly?我该如何解决这个问题,以便正确保存所有内容?

I want to save a Document and at the same time get that ID generated by MongoDB to save to another API.我想保存一个文档,同时获取由 MongoDB 生成的 ID 以保存到另一个 API。

public Mono<BankAccountDTO> save(BankAccountDTO bankAccount) {
    
    return mongoRepository.save(AppUtils.dtoToEntity(bankAccount))
        .doOnNext(d -> {
            
            CustomerRoleDTO cDto = new CustomerRoleDTO();
            cDto.setBankAccountid(d.getId());
            cDto.setClientId(bankAccount.getCustomerId());
            
            webClient.post()
                .uri("http://localhost:9292/api/v1/example")
                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .body(Mono.just(cDto), CustomerRoleDTO.class)
                .retrieve()
                .bodyToMono(CustomerRoleDTO.class);
            
        }).map(AppUtils::entityToDTO);

}

you are breaking the chain by not handling the return from your wbClient call, so that reactor can't fulfill assembly time.您通过不处理 wbClient 调用的返回来破坏链条,因此反应器无法满足组装时间。

(i have not checked against a compiler, but something like this) (我没有检查过编译器,但类似这样)

public Mono<BankAccountDTO> save(BankAccountDTO bankAccount) {
    return mongoRepository.save(AppUtils.dtoToEntity(bankAccount))
        .flatMap(d -> {
            
        CustomerRoleDTO cDto = new CustomerRoleDTO();
        cDto.setBankAccountid(d.getId());
        cDto.setClientId(bankAccount.getCustomerId());
            
        // you cant ignore the return
        return webClient.post()
                .uri("http://localhost:9292/api/v1/example")
                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .body(Mono.just(cDto), CustomerRoleDTO.class)
                .retrieve()
                .bodyToMono(CustomerRoleDTO.class)
                .thenReturn(d);
    });
}

here you can read more about assembly time .在这里您可以阅读有关assembly time的更多信息。

Assembly vs Subscription 组装与订阅

Use flatmap instead of doOnNext使用flatmap代替doOnNext

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM