1

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

  1. 调用 webclient1.get() -> response1
  2. 使用 reponse1 像这样调用第二个 api: webclient2.getDetails(response1.getId())
  3. 使用 reponse1 像这样调用第三个 api: webclient3.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 不确定错误在哪里

4

1 回答 1

1

您应该链接所有操作以创建反应流。您可以使用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;
                })
        );
}
于 2021-10-21T06:07:54.367 回答