使用 Web 客户端发出下游请求时"java.util.NoSuchElementException: Context is empty"异常



我正在尝试从2.2.0.RELEASE升级到spring boot 2.6.6。迁移后,我发现在使用webclient进行下游调用时,我得到了下面提到的异常。所以我开始检查较低版本的spring boot,我发现我的实现在spring boot 2.6.3中工作得很好。但是升级到spring boot 2.6.4版本,我得到这个错误。

JDK版本:openjdk 17.0.2

误差:

类org.springframework.web.react .function.client. webclientrequestexception |原因:java.util.NoSuchElementException: Context is empty |异常消息:Context is empty;嵌套异常是java.util.NoSuchElementException: Context is empty | StackTrace: org.springframework.web.react .function.client. exchangefunctions $DefaultExchangeFunction.lambda$wrapException$9(ExchangeFunctions.java:141)

在spring boot 2.6.4中发生了什么变化,我得到了这个错误?我可以对我的代码做什么改变来解决这个问题。

@PostConstruct
public void init() {
webClient = WebClient.create();

}
public Mono<?> postRequest(final String url, final Object request,
final MultiValueMap headers, final MediaType contentType, final MediaType acceptType) {
Mono<?> response;
try {
URI uri = new URI(url);
long webClientStartTime = System.currentTimeMillis();
response = webClient.post().uri(uri)
.contentType(contentType)
.headers(httpHeaders -> {
if (Objects.nonNull(headers)) {
httpHeaders.addAll(headers);
}
})
.bodyValue(request)
.accept(acceptType)
.exchangeToMono(clientResponse -> {
log.info("clientResponse.statusCode(): {}, path: {}, webClient latency: {}",
clientResponse.statusCode(), uri.getPath(), System.currentTimeMillis() - webClientStartTime);
if (!clientResponse.statusCode().is2xxSuccessful()) {
return Mono.error(new BaseException("Not success response received from downstream. HttpCode: " +  clientResponse.statusCode()));
}
return clientResponse.bodyToMono(String.class);
})
.timeout(Duration.ofMillis(500))
.doOnError(throwable -> log.error("clientResponse error: {}, path: {}, webclient latency: {}",
throwable, uri.getPath(), System.currentTimeMillis() - webClientStartTime));
return response;
} catch (Exception ex) {
log.error("Some exception while processing post request. Error: {}",  ex.getMessage());
}
return null;
}

根据@VioletaGeorgieva的建议,升级到Spring boot 2.6.8已经修复了这个问题。

最新更新