通过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"));
...
}