【问题标题】:Spring webclient using generic return type使用通用返回类型的 Spring webclient
【发布时间】:2020-07-27 15:41:33
【问题描述】:

我写了下面的代码,我想在方法调用中返回一个泛型类型(类响应)而不是 JsonNode。如果我使用泛型类型响应对象,我在 bodyToMono 调用中遇到错误。那么如何使用以下代码检索泛型类型响应。

 public JsonNode exchange(WebClient webClient, WebClientRequest requestDetails, Class<V> response) throws IOException {
    if (requestDetails.getHttpMethod() == null) {
        requestDetails.setHttpMethod(HttpMethod.GET);
    }
    if (requestDetails.getParams() == null) {
        requestDetails.setParams(new HashMap<>());
    }
    JsonNode result = null;
    try {
        result = webClient
                .method(requestDetails.getHttpMethod())
                .uri(requestDetails.getServiceUrl(), requestDetails.getParams())
                .headers(httpHeaders -> httpHeaders.setAll(requestDetails.getHeaders()))
                .exchange()
                .flatMap(ClientResponse -> ClientResponse.bodyToMono(JsonNode.class))
                .retryWhen(Retry.any()
                        .fixedBackoff(Duration.ofSeconds(5))
                        .retryMax(5))
                .delaySubscription(Duration.ofSeconds(10))
                .block();
    } catch (WebClientResponseException ex) {
        log.error("WebClientResponseException in Webclient call : ", ex.getMessage());
    } catch (Exception ex) {
        log.error("Exception in Webclient call : ", ex.getMessage());
    }
    return result;
}

【问题讨论】:

  • 如果您有接口及其实现,请使用@JsonTypeInfo。在其他情况下,只需反序列化为 Object.class(很可能是 Map 映射)并从那里开始。

标签: java spring reactive-programming spring-webclient


【解决方案1】:

您的问题出在方法声明中。你已经放了:

public JsonNode exchange(.......

这样,您将创建一个名为“exchange”的方法,该方法返回 JsonNode 对象。要返回通用对象,您需要更改声明:

public <YourClassObject> exchange(......

为此,您可以使用泛型 Object 类:

public Object exchange(...

但是,当调用方法 exchante() 时,你需要转换结果。

为避免此类问题,您可以使用 T 对象。例如,您可以阅读更多 here

【讨论】:

  • 我更改了方法签名,如 -> public V exchange(WebClient webClient, WebClientRequest requestDetails, V responseType) 抛出 IOException 但方法中的这一行给出错误 -> .flatMap(ClientResponse -> ClientResponse .bodyToMono(responseType.getClass())) // lambda 表达式中使用的错误变量应该是 final 或有效 final
猜你喜欢
  • 2021-01-11
  • 2018-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-22
  • 2017-01-21
  • 1970-01-01
相关资源
最近更新 更多