概述
通过http做接口调用请求的时候,常常会因为网络抖动或者其他未知原因,造成接口在某个瞬间访问不了。此时需要增加重试机制。
private static HttpRequestRetryHandler httpRequestRetryHandler =null;
static {
httpRequestRetryHandler = new HttpRequestRetryHandler() {
@Override
public boolean retryRequest(IOException exception, int retryTimes, HttpContext context) {
logger.error("retryRequest:"+retryTimes);
if (retryTimes >= 3) {
return false;
}
if (exception instanceof ConnectTimeoutException || exception instanceof NoHttpResponseException || exception instanceof SocketTimeoutException
|| !(exception instanceof UnknownHostException) || !(exception instanceof InterruptedIOException) || !(exception instanceof SSLException)
|| !(exception instanceof SSLHandshakeException)) {
return true;
}else {
logger.error("未记录的请求异常:" + exception.getClass());
}
HttpClientContext clientContext = HttpClientContext.adapt(context);
HttpRequest request = clientContext.getRequest();
boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
if (idempotent) {
// 如果请求被认为是幂等的,那么就重试。即重复执行不影响程序其他效果的
return true;
}
return false;
}
};
}
public static CloseableHttpClient createSSLClientDefault(Boolean bool) {
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
// 信任所有
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
if (bool)
return HttpClients.custom().setRetryHandler(httpRequestRetryHandler).setSSLSocketFactory(sslsf).build();
} catch (Exception e) {
e.printStackTrace();
}
return HttpClients.custom().setRetryHandler(httpRequestRetryHandler).build();
//.setConnectionManager(connectionManager).setServiceUnavailableRetryStrategy(serviceUnavailableRetryStrategy)
}
public static String userPost(String url, String token,String jsonString){
CloseableHttpClient httpClient = createSSLClientDefault(StringUtils.isNotBlank(url) && url.startsWith("https"));
...
}
最后
以上就是淡定春天为你收集整理的HttpClient重试机制的全部内容,希望文章能够帮你解决HttpClient重试机制所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复