如何 return 包含 Reactive Mono 和 Flux 的 Reactive Flux?

How to return a Reactive Flux that contains a Reactive Mono and Flux?

我是响应式编程的新手,运行 遇到了这个问题:

[
    {
        "customerDTO": {
            "scanAvailable": true
        },
        "bankAccountDTOs": {
            "scanAvailable": true,
            "prefetch": -1
        }
    }
]

DTO:

public class ResponseClientDTO {
    private Mono<CustomerDTO> customerDTO;
    private Flux<BankAccountDTO> bankAccountDTOs;
}

服务:

public Flux<ResponseClientDTO> getCustomerWithBankAccounts(String customerId){
    Flux<BankAccountDTO> bankAccounts = webClient
        .get()
        .uri(uriBuilder -> 
                uriBuilder.path("customers")
                .queryParam("customerId", customerId).build())
        .accept(MediaType.APPLICATION_JSON)
        .retrieve()
        .bodyToFlux(BankAccountDTO.class);
        
    
    Mono<CustomerDTO> cMono = findOne(customerId);
    
    ResponseClientDTO responseClientDTO = new ResponseClientDTO();
    responseClientDTO.setBankAccountDTOs(bankAccounts);
    responseClientDTO.setCustomerDTO(cMono);
    
    return Flux.just(responseClientDTO);
}

我从另一个 API 查询一个端点,它 returns 一个 Flux<BankAccounts> 。我想让客户知道他所有的银行账户。

这不是您想要的反应式堆栈。首先,更改您的 DTO(数据传输对象),使其不包含 MonoFlux,而是包含 CustomerDTOList<BankAccountDTO>

public class ResponseClientDTO {
    private CustomerDTO customerDTO;
    private List<BankAccountDTO> bankAccountDTOs;
}

然后,您需要将方法重新安排为 return 和 Mono<ResponseClientDTO>,并更改逻辑以处理 FluxMono:

public Mono<ResponseClientDTO> getCustomerWithBankAccounts(String customerId){
    Flux<BankAccountDTO> bankAccounts = webClient
        .get()
        .uri(uriBuilder -> 
                uriBuilder.path("customers")
                .queryParam("customerId", customerId).build())
        .accept(MediaType.APPLICATION_JSON)
        .retrieve()
        .bodyToFlux(BankAccountDTO.class);
        
    Mono<CustomerDTO> cMono = findOne(customerId);
    
    return bankAccounts.collectList().zipWith(cMono).map(data -> {
        ResponseClientDTO responseClientDTO = new ResponseClientDTO();
        responseClientDTO.setBankAccountDTOs(data.getT1());
        responseClientDTO.setCustomerDTO(data.getT2());
    })
}

(抱歉有任何 Java 错别字,但在这一点上我已经习惯了 Kotlin)。

考虑查看以下有用的在线资源: