java apache client,使用 java apache http client 增加重连 retry

1,使用apache client

一般使用http的时候都是短链接。所以失败的情况经常发生。

于是想retry 重连增加成功概率。但是又想找一个优美的解决办法。

而不是自己写代码 retry。

2,使用retryHandler

全部重试代码:

import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.NameValuePair;

import org.apache.http.client.HttpClient;

import org.apache.http.client.entity.UrlEncodedFormEntity;

import org.apache.http.client.methods.CloseableHttpResponse;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.impl.client.*;

import org.apache.http.message.BasicNameValuePair;

import org.apache.http.util.EntityUtils;

import java.util.ArrayList;

import java.util.List;

public class TestHttp {

public static void main(String[] args) {

for (int i = 1; i < 1000; i++) {

String str = test();

if (str.equals("")) {

System.out.printf("########## error ########");

} else {

System.out.println(str);

}

}

}

public static String test() {

String str = "";

DefaultHttpClient httpClient = new DefaultHttpClient();

DefaultHttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler(5, true);

httpClient.setHttpRequestRetryHandler(retryHandler);

HttpPost httpPost = new HttpPost("http://www.baidu.com/");

List nvps = new ArrayList();

nvps.add(new BasicNameValuePair("username", "vip"));

nvps.add(new BasicNameValuePair("password", "secret"));

//httpPost.setEntity(new UrlEncodedFormEntity(nvps));

try {

System.out.println("cout:" + retryHandler.getRetryCount());

HttpResponse response2 = httpClient.execute(httpPost);

str = response2.getStatusLine().toString();

System.out.println(str);

HttpEntity entity2 = response2.getEntity();

// do something useful with the response body

// and ensure it is fully consumed

EntityUtils.consume(entity2);

} catch (Exception e) {

e.printStackTrace();

} finally {

httpPost.abort();

httpClient.getConnectionManager().shutdown();

}

return str;

}

}

比如访问大百度,访问次数多了只会被拦截掉呢。

3,分析下

主要是使用了 DefaultHttpRequestRetryHandler

这个实现了

public interface HttpRequestRetryHandler {

boolean retryRequest(IOException var1, int var2, HttpContext var3);

}

重试接口。DefaultHttpRequestRetryHandler 实现了这个接口就可以了。

在初始化的时候

public MyDefaultHttpRequestRetryHandler(int retryCount, boolean requestSentRetryEnabled) {

this(retryCount, requestSentRetryEnabled, Arrays.asList(InterruptedIOException.class, UnknownHostException.class, ConnectException.class, SSLException.class));

}

这是个有意思的设计,放入了几个 异常,然后如果出现异常之后就会重试。

public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {

凡是发现了 IOException 就开始进行重试操作。

直到执行了 n次重试之后为止。

通过日志抓到 发现 java.net.SocketException 重试了一次。

SocketException 也是继承了 IOException。发出网络异常之后就进入重试了。

4,总结

使用 apache retry 非常方便,只需要两行代码就可以完成。

非常的方便。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Sure, here's an example of how to implement retry in Java for an HTTP request using the Apache HttpClient library: ```java import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.protocol.HttpContext; import java.io.IOException; public class HttpRequestRetry { private static final int MAX_RETRIES = 3; public static void main(String[] args) throws IOException { HttpClient httpClient = HttpClientBuilder.create().build(); HttpGet httpGet = new HttpGet("https://www.example.com"); int retryCount = 0; boolean success = false; while (retryCount < MAX_RETRIES && !success) { try { httpClient.execute(httpGet, (HttpContext) null); success = true; } catch (IOException e) { System.out.println("Request failed, retrying..."); retryCount++; } } if (success) { System.out.println("Request succeeded after " + retryCount + " retries."); } else { System.out.println("Request failed after " + retryCount + " retries."); } } } ``` In this example, we create an `HttpClient` instance using the `HttpClientBuilder` class, and then create an `HttpGet` request object for the URL we want to retrieve. We then loop through the request up to a maximum number of retries (in this case, 3), attempting the request each time and catching any `IOException` that is thrown. If the request succeeds, we set the `success` flag to true and exit the loop. If the request fails after the maximum number of retries, we print a failure message.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值