使用 java apache http client 增加重连 retry

时间:2025-02-18 16:30:37

本文的原文连接是: /freewebsys/article/details/78860325
未经博主允许不得转载。
博主地址是:/freewebsys

1,使用apache client


一般使用http的时候都是短链接。所以失败的情况经常发生。
于是想retry 重连增加成功概率。但是又想找一个优美的解决办法。
而不是自己写代码 retry。

参考代码:
/java-api-examples/?api=

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("/");
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        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, (InterruptedIOException.class, UnknownHostException.class, ConnectException.class, SSLException.class));
    }

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

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

凡是发现了 IOException 就开始进行重试操作。
直到执行了 n次重试之后为止。

通过日志抓到 发现 重试了一次。
SocketException 也是继承了 IOException。发出网络异常之后就进入重试了。

4,总结


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

本文的原文连接是: /freewebsys/article/details/78860325
未经博主允许不得转载。
博主地址是:/freewebsys