【发布时间】:2020-11-04 09:13:28
【问题描述】:
我正在使用 WebFlux 和 WebClient,我需要使用两个 API 并合并其响应。
第一个 API 接收类型和文档编号并返回一个列表,其中包含一个包含客户数据的元素(这就是它的定义方式)。
第二个 API 接收客户端 ID 并返回客户付款列表。
我需要使用这两个 API 并返回一个包含客户数据及其付款的实体。
API 客户响应
public class CustomerResponseApi {
private List<CustomerApi> clientList;
}
public class CustomerApi {
private int customerId;
private String documentNumber;
private String documentType;
private String firstName;
private String lastName;
}
API 支付响应
public class PaymentResponseApi {
private int customerId;
private LocalDate paymentDate;
private float amount;
private String paymentType;
}
最后我应该有这个
CustomerResponse.java
public class CustomerResponse {
private int customerId;
private String documentNumber;
private String documentType;
private String firstName;
private String lastName;
private List<PaymentResponseApi> payments;
}
我有一个代理类负责进行 API 调用
CustomerProxy.java
public class CustomerProxy {
@Value("${api.base-url}")
private String baseUrl;
public Mono<CustomerResponseApi> getCustomer(String documentType, String documentNumber) {
log.info("baseUrl: {}", baseUrl);
WebClient webClient = WebClient.create(baseUrl);
return webClient.get()
.uri(uri -> uri
.path("/customers")
.queryParam("documentNumber", documentNumber)
.queryParam("documentType", documentType)
.build()
)
.retrieve()
.bodyToMono(CustomerResponseApi.class);
}
}
PaymentProxy.java
public class PaymentProxy {
@Value("${api.base-url}")
private String baseUrl;
public Flux<PaymentResponseApi> getCustomerPayment(int customerId) {
log.info("baseUrl: {}", baseUrl);
WebClient webClient = WebClient.create(baseUrl);
return webClient.get()
.uri(uri -> uri
.path("/payments")
.queryParam("customerId", customerId)
.build()
)
.retrieve()
.bodyToFlux(PaymentResponseApi.class);
}
}
还有一个负责合并响应的服务 CustomerServiceImpl.java
public class CustomerServiceImpl implements CustomerService {
@Autowired
private CustomerProxy customerProxy;
@Autowired
private PaymentProxy paymentProxy;
@Override
public Mono<CustomerResponse> getCustomerAndPayments(String documentType, String documentNumber) {
return customerProxy.getCustomer(documentType, documentNumber).flatMap(resp -> {
CustomerApi customerApi = resp.getClientList().get(0); //always returns one customer
// Here is my problem, because getCustomerPayment method returns a Flux
List<PaymentResponseApi> payments = paymentProxy.getCustomerPayment(customerApi.getCustomerId());
CustomerResponseBuilder customerBuilder = CustomerResponse.builder()
.customerId(customerApi.getCustomerId())
.documentNumber(customerApi.getDocumentNumber())
.documentType(customerApi.getDocumentType())
.firstName(customerApi.getFirstName())
.lastName(customerApi.getLastName())
.payments(payments);
return Mono.just(customerBuilder.build());
});
}
}
【问题讨论】:
标签: java reactive-programming spring-webflux spring-webclient