HttpClient的NoHttpResponse问题
调用第三方接口时会报NoHttpResponse异常,原因是上次的连接已经断掉了,但是客户端并未知道,复用上次连接就报错了,所以要解决这个问题,就是要校验上次链接是否断掉了
1. httpClient已经给我们实现了这个,setRetryHandler
public static RestTemplate builRestTemplate() {
SSLConnectionSocketFactory sf = null;
try {
sf = new SSLConnectionSocketFactory(new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(), new NoopHostnameVerifier());
} catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
logger.error("SSL related failure: {} ", e.getMessage());
throw new CloudChefException("SSL error");
}
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sf).setRetryHandler((exception, executionCount, context) -> {
if (executionCount > 3) { //重试3次,大于3次则结束
logger.warn("Maximum tries reached for client http pool ");
return false;
}
if (exception instanceof org.apache.http.NoHttpResponseException) { //如果是NoHttpResponseException则进行重试
logger.warn("No response from server on " + executionCount + " call");
return true;
}
return false;
}).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
configureTimeout(requestFactory);
return new RestTemplate(requestFactory);
}
private static void configureTimeout(HttpComponentsClientHttpRequestFactory factory) {
//默认http request超时设置
factory.setReadTimeout(120_1000);
factory.setConnectTimeout(15_1000);
factory.setConnectionRequestTimeout(15_1000);
}
2.或者使用 DefaultHttpRequestRetryHandler
HttpClientBuilder clientBuilder = HttpClients.custom(); clientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(3, true));
对于这个问题的分析有一个不错的博客,写的不错:https://czjxy881.github.io/java,nginx/%E8%AE%B0HttpClient%E7%9A%84NoHttpResponse%E9%97%AE%E9%A2%98/
作者:guanbin —— 纵码万里千山
出处:https://www.cnblogs.com/guanbin-529/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。