[英]How to return a Reactive Flux that contains a Reactive Mono and Flux?
I'm new to reactive programming and ran into this problem:我是响应式编程的新手,遇到了这个问题:
[
{
"customerDTO": {
"scanAvailable": true
},
"bankAccountDTOs": {
"scanAvailable": true,
"prefetch": -1
}
}
]
DTO: DTO:
public class ResponseClientDTO {
private Mono<CustomerDTO> customerDTO;
private Flux<BankAccountDTO> bankAccountDTOs;
}
Service:服务:
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);
}
I query an endpoint from another API, and it returns a Flux<BankAccounts>
.我从另一个 API 查询一个端点,它返回一个
Flux<BankAccounts>
。 I want to get the client with all his bank accounts.我想得到客户的所有银行账户。
That is not what you want in a reactive stack.这不是您在反应式堆栈中想要的。 First, change your DTO so that it does't include
Mono
and Flux
, but CustomerDTO
and List<BankAccountDTO>
instead:首先,更改您的 DTO,使其不包含
Mono
和Flux
,而是包含CustomerDTO
和List<BankAccountDTO>
:
public class ResponseClientDTO {
private CustomerDTO customerDTO;
private List<BankAccountDTO> bankAccountDTOs;
}
Then, you need to rearrange your method to return a Mono<ResponseClientDTO>
instead and to change the logic to deal with Flux
and Mono
:然后,您需要重新安排方法以返回
Mono<ResponseClientDTO>
并更改处理Flux
和Mono
的逻辑:
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());
})
}
(Sorry for any Java typo but at this point I am too used to Kotlin). (很抱歉有任何 Java 错字,但此时我已经习惯了 Kotlin)。
Consider taking a look at the following useful online resources:考虑查看以下有用的在线资源:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.