需求
在接口开发中,需要请求第三方http接口获取数据,因服务器网络波动异常,有时会导致请求第三方http接口异常,因此采用请求重试机制来解决这个问题。
核心代码
/**
* @param url: 接口url
* @param maxRetryTimes:设置最大重试次数,决定了请求失败后最多重试的次数。
* @param retryInterval:即每次重试之间的延迟时间,单位毫秒
*/
public Response retryHttpRequest(String url, int maxRetryTimes, int retryInterval) throws Exception {
int retryCount = 0;
Response response = null;
while (retryCount < maxRetryTimes) {
try {
response = invoker.doPost(url);
break;
} catch (Exception e) {
retryCount++;
log.info("【网络出现波动异常,正在进行重试】:" + retryCount);
Thread.sleep(retryInterval);
}
}
return response;
}
/**
* 检查域名是否可用
* @param domainName:域名
*/
public static boolean isDomainAvailable(String domainName) {
try {
InetAddress inetAddress = InetAddress.getByName(domainName);
return inetAddress.isReachable(5000); // 设置超时时间为5秒
} catch (UnknownHostException e) {
System.out.println("域名解析失败: " + e.getMessage());
} catch (IOException e) {
System.out.println("网络连接异常: " + e.getMessage());
}
return false;
}
参考博客
1.Java调用Http请求重试机制
2.解决问题Caused by: java.net.UnknownHostException
3.三种方法判断域名能否访问