2

Is there a way to convert Mono objects to java Pojo? I have a web client connecting to 3rd party REST service and instead of returning Mono I have to extract that object and interrogate it.

All the examples I have found return Mono<Pojo> but I have to get the Pojo itself. Currently, I am doing it by calling block() on Pojo but is there a better way to avoid block?

The issue with the block is that after few runs it starts throwing some error like block Terminated with error.

 public MyPojo getPojo(){
     return myWebClient.get()
                .uri(generateUrl())
                .headers(createHttpHeaders(headersMap))
                .exchange()
                .flatMap(evaluateResponseStatus())
                .block();
}


private Function<ClientResponse, Mono<? extends MyPojo>> evaluateResponseStatus() {
      return response -> {
            if (response.statusCode() == HttpStatus.OK) {
                return response.bodyToMono(MyPojo.class);
            }
            if (webClientUtils.isError(response.statusCode())) {
                throw myHttpException(response);
                // This invokes my exceptionAdvice
                // but after few runs its ignored and 500 error is returned.
            }
            return Mono.empty();
        };
    }
4

2 回答 2

7

阻止对反应流中的值进行操作并不是一个好主意。Project Reactor 为您提供了一系列运算符来处理流中的对象。

在您的情况下,您可以编写getPojo()如下方法:

public Mono<MyPojo> getPojo() {
     return myWebClient.get()
            .uri(generateUrl())
            .headers(createHttpHeaders(headersMap))
            .retrieve()
            .onStatus(status -> webClientUtils.isError(status), 
                      response -> Mono.error(myHttpException(response))
            .bodyToMono(MyPojo.class)
}

请注意,使用onStatus方法,我们替换了您示例中的整个evaluateResponseStatus方法。

您将使用此方法,如下所示:

// some method
...
getPojo()
    .map(pojo -> /* do something with the pojo instance */)
...

我强烈建议您查看在 Project Reactor 文档中转换现有序列。

于 2018-06-03T16:09:37.677 回答
0

由于不推荐使用 Webclient.block(),从传入的 httpresponse 检索值的另一种方法是在调用应用程序中创建一个具有所需字段的 POJO。然后,一旦收到 Mono,使用 Mono.subscribe(),在 subscribe 中添加一个 lambda 函数,输入为 x,以使用 x.getters() 检索各个字段。这些值可以打印在控制台上或分配给本地 var 以进行进一步处理。这有两个方面的帮助:-

  1. 避免可怕的 .block()
  2. 拉取大量数据时保持调用异步。这是实现预期结果的许多其他方法之一。
于 2021-10-15T08:29:02.840 回答