【发布时间】: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