Spring webflux,使用api1的响应来调用api2和api3,并使用它来构建最终的响应



我需要从3个api调用构建一个JSON。

  1. 调用webclient .get() ->response1
  2. 使用response1调用第二个apiwebclient2.getDetails(response1.getId())
  3. 使用response1调用第三个apiwebclient3.getDetails(response1.getId())

示例代码
private Mono<RequestPayload> buildRequestPayload(Request request) {
RequestPayload requestPayload = null;
Mono<T> response1 = webclient1.get(request.getId());
response1.flatMap(res -> {
return webclient2.getDetails(res.getId());
//not sure how to call webclient3.getDetails(response1.getId()) after return statement
});
//I think the final one should be something like this (not sure though) but did not get until here
return Mono.zip(respons1, resppnse2, response3).flatMap(finalResponse -> {
requestPayload.setResponse1(finalResponse.getT1());
requestPayload.setResponse2(finalResponse.getT2());
requestPayload.setResponse3(finalResponse.getT3());
});
}

我在管道中得到null不确定错误在哪里

为了创建响应式流,您应该链接所有操作。您可以使用flatmapmap操作符来完成此操作:

private Mono<RequestPayload> buildRequestPayload(Request request) {
return executeRequest1()
.flatMap(request1Result ->
executeRequest2()
.map(request2Result -> RequestPayload.builder()
.response1(request1Result)
.response2(request2Result)
.build()))
.flatMap(requestPayload ->
executeRequest3()
.map(request3Result -> {
requestPayload.response3(request3Result);
return requestPayload;
})
);
}

相关内容

  • 没有找到相关文章

最新更新