我有三个 Mono 的 json 字符串,如下所示
Mono<String> strInventoryResp=invWebClient.get().
uri("/findATSInventory?skuId="+skuId).
exchange().flatMap(resp-> resp.bodyToMono(String.class));
Mono<String> strProductResponse=productClient.get().
uri("/v2/products/id/"+skuId).
exchange().flatMap(resp-> resp.bodyToMono(String.class));
Mono<String> strItemResp=productClient.get().
uri("/v2/items?id="+skuId).
exchange().flatMap(resp-> resp.bodyToMono(String.class));
我想将它合并到一个 Flux of Json 字符串中,这样结果也是一个 json 字符串。
我已经尝试了 Flux.merge 静态方法,但显然它不会以 json 格式返回,如下所示
Flux.merge(strProductResponse,strItemResp,strInventoryResp);
如何返回组合单声道响应的 Flux 以便在调用调用此方法的 Controller 时在浏览器中返回有效的 JSON 字符串流?
编辑:
我的问题陈述是使用 Web Flux 异步调用这三个 API 并将结果合并为一个。 Controller 将调用此方法并返回 UI 的组合结果。
有没有其他方法可以解决这个问题?
最佳答案
这就是我将如何解决它。
@Test
public void buildResponse() {
final Mono<String> customerName = Mono.just("customer name");
final Mono<String> customerPreference = Mono.just("customer preference");
final Mono<String> cusomterShippingInformation = Mono.just("cusomter shipping information");
final Mono<JsonObjectYouWantToReturn> returnThisAsAResponse = customerName
.map(Builder::new)
.zipWith(customerPreference)
.map(t -> t.getT1().withCustomerPreference(t.getT2()))
.zipWith(cusomterShippingInformation)
.map(t -> t.getT1().withCustomerShippingInformation(t.getT2()))
.map(Builder::build);
}
private class Builder {
private String customerName;
private String customerPreference;
private String customerShippingInfo;
public Builder(String customerName) {
this.customerName = customerName;
}
public Builder withCustomerPreference(String customerPreference) {
this.customerPreference = customerPreference;
return this;
}
public Builder withCustomerShippingInformation(String t3) {
this.customerShippingInfo = t3;
return this;
}
public JsonObjectYouWantToReturn build() {
return new JsonObjectYouWantToReturn(customerName, customerPreference, customerShippingInfo);
}
}
private class JsonObjectYouWantToReturn {
public final String customerName;
public final String customerPreference;
public final String customerShippingInfo;
public JsonObjectYouWantToReturn(String customerName, String customerPreference, String customerShippingInfo) {
this.customerName = customerName;
this.customerPreference = customerPreference;
this.customerShippingInfo = customerShippingInfo;
}
}
关于spring-webflux - Spring 2.0 WebFlux : Merge multiple Mono<String> , 其中 string 是转换为 string 的 json,转换为单个 Flux<String>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53814095/