我需要从3个api调用构建一个JSON。
- 调用webclient .get() ->response1
- 使用response1调用第二个apiwebclient2.getDetails(response1.getId())
- 使用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不确定错误在哪里
为了创建响应式流,您应该链接所有操作。您可以使用flatmap
和map
操作符来完成此操作:
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;
})
);
}