HttpClient 4.5.2-(四)连接超时的配置

紧接上一节,本节记录 【连接超时的配置】
  工作中有这样一个需求,要对上千台的服务器进行更新测试,这是需要开几百个线程做并发测试,每个线程中都有N次的Http请求,看服务器是否可以顶得住。但是碰到一个问题,那就是访问的过程中有些线程莫名其妙就不访问了,观察服务器端,并没有请求进来。开始各种怀疑,是线程自己死掉了?还是Windows对每个进程有线程的限制?亦或者是HttpClient对总连接数量有限制?
  最后经过每一步的测试和排查,确定问题在于两方面:

  1. httpClient客户端连接对象并没有配置连接池,使用默认的连接池不能支持那么多的并发量。
  2. 没有给每一次的连接设置超时时间获取连接超时 请求超时 响应超时,如果没有设置超时时间,连接可能会一直存在阻塞,所以线程一直停在那里,其实线程并没有死掉
也就是说,我们只需把上述两个问题解决问题就迎刃而解了。本节先说连接超时时间的设置。

上代码:
package com.lynchj.writing;

/**
 * Http请求工具类
 * 
 * @author 大漠知秋
 */
public class HttpRequestUtils {
    
}
  • 获取带超时间的httpClient客户端连接对象
/**
 * 获取Http客户端连接对象
 * 
 * @param timeOut 超时时间
 * @return Http客户端连接对象
 */
public static HttpClient getHttpClient(Integer timeOut) {
    // 创建Http请求配置参数
    RequestConfig requestConfig = RequestConfig.custom()
        // 获取连接超时时间
        .setConnectionRequestTimeout(timeOut)
        // 请求超时时间
        .setConnectTimeout(timeOut)
        // 响应超时时间
        .setSocketTimeout(timeOut)
        .build();
    
    // 创建httpClient
    return HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
}
  • POST请求方法
/**
 * GET请求
 * 
 * @param url 请求地址
 * @param timeOut 超时时间
 * @return
 */
public static String httpGet(String url, Integer timeOut) {
    String msg = "-1";
    
    // 获取客户端连接对象
    CloseableHttpClient httpClient = getHttpClient(timeOut);
    // 创建GET请求对象
    HttpGet httpGet = new HttpGet(url);
    
    CloseableHttpResponse response = null;
    
    try {
        // 执行请求
        response = httpClient.execute(httpGet);
        // 获取响应实体
        HttpEntity entity = response.getEntity();
        // 获取响应信息
        msg = EntityUtils.toString(entity, "UTF-8");
    } catch (ClientProtocolException e) {
        System.err.println("协议错误");
        e.printStackTrace();
    } catch (ParseException e) {
        System.err.println("解析错误");
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("IO错误");
        e.printStackTrace();
    } finally {
        if (null != response) {
            try {
                response.close();
            } catch (IOException e) {
                System.err.println("释放链接错误");
                e.printStackTrace();
            }
        }
    }
    
    return msg;
}
  • 测试main方法
public static void main(String[] args) {
        
    System.out.println(httpGet("http://www.baidu.com", 6000));
    
}

经多次测试结果,发现如果仅仅这是这么配置的话,还是会存在设置超时时间不起作用的情况,最后排查结果

  • 经过修改后的获取客户端连接工具的方法
/**
 * 获取Http客户端连接对象
 * 
 * @param timeOut 超时时间
 * @return Http客户端连接对象
 */
public static CloseableHttpClient getHttpClient(Integer timeOut) {
    // 创建Http请求配置参数
    RequestConfig requestConfig = RequestConfig.custom()
        // 获取连接超时时间
        .setConnectionRequestTimeout(timeOut)
        // 请求超时时间
        .setConnectTimeout(timeOut)
        // 响应超时时间
        .setSocketTimeout(timeOut)
        .build();
    
    /**
     * 测出超时重试机制为了防止超时不生效而设置
     *  如果直接放回false,不重试
     *  这里会根据情况进行判断是否重试
     */
    HttpRequestRetryHandler retry = new HttpRequestRetryHandler() {
        @Override
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            if (executionCount >= 3) {// 如果已经重试了3次,就放弃
                return false;
            }
            if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试
                return true;
            }
            if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
                return false;
            }
            if (exception instanceof InterruptedIOException) {// 超时
                return true;
            }
            if (exception instanceof UnknownHostException) {// 目标服务器不可达
                return false;
            }
            if (exception instanceof ConnectTimeoutException) {// 连接被拒绝
                return false;
            }
            if (exception instanceof SSLException) {// ssl握手异常
                return false;
            }
            HttpClientContext clientContext = HttpClientContext.adapt(context);
            HttpRequest request = clientContext.getRequest();
            // 如果请求是幂等的,就再次尝试
            if (!(request instanceof HttpEntityEnclosingRequest)) {
                return true;
            }
            return false;
        }
    };
    
    // 创建httpClient
    return HttpClients.custom()
            // 把请求相关的超时信息设置到连接客户端
            .setDefaultRequestConfig(requestConfig)
            // 把请求重试设置到连接客户端
            .setRetryHandler(retry)
            .build();
}
  • 最后完整代码
package com.lynchj.writing;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.UnknownHostException;

import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpRequest;
import org.apache.http.NoHttpResponseException;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

/**
 * Http请求工具类
 * 
 * @author 大漠知秋
 */
public class HttpRequestUtils {
    
    /**
     * 获取Http客户端连接对象
     * 
     * @param timeOut 超时时间
     * @return Http客户端连接对象
     */
    public static CloseableHttpClient getHttpClient(Integer timeOut) {
        // 创建Http请求配置参数
        RequestConfig requestConfig = RequestConfig.custom()
            // 获取连接超时时间
            .setConnectionRequestTimeout(timeOut)
            // 请求超时时间
            .setConnectTimeout(timeOut)
            // 响应超时时间
            .setSocketTimeout(timeOut)
            .build();
        
        /**
         * 测出超时重试机制为了防止超时不生效而设置
         *  如果直接放回false,不重试
         *  这里会根据情况进行判断是否重试
         */
        HttpRequestRetryHandler retry = new HttpRequestRetryHandler() {
            @Override
            public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
                if (executionCount >= 3) {// 如果已经重试了3次,就放弃
                    return false;
                }
                if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试
                    return true;
                }
                if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
                    return false;
                }
                if (exception instanceof InterruptedIOException) {// 超时
                    return true;
                }
                if (exception instanceof UnknownHostException) {// 目标服务器不可达
                    return false;
                }
                if (exception instanceof ConnectTimeoutException) {// 连接被拒绝
                    return false;
                }
                if (exception instanceof SSLException) {// ssl握手异常
                    return false;
                }
                HttpClientContext clientContext = HttpClientContext.adapt(context);
                HttpRequest request = clientContext.getRequest();
                // 如果请求是幂等的,就再次尝试
                if (!(request instanceof HttpEntityEnclosingRequest)) {
                    return true;
                }
                return false;
            }
        };
        
        // 创建httpClient
        return HttpClients.custom()
                // 把请求相关的超时信息设置到连接客户端
                .setDefaultRequestConfig(requestConfig)
                // 把请求重试设置到连接客户端
                .setRetryHandler(retry)
                .build();
    }
    
    /**
     * GET请求
     * 
     * @param url 请求地址
     * @param timeOut 超时时间
     * @return
     */
    public static String httpGet(String url, Integer timeOut) {
        String msg = "-1";
        
        // 获取客户端连接对象
        CloseableHttpClient httpClient = getHttpClient(timeOut);
        // 创建GET请求对象
        HttpGet httpGet = new HttpGet(url);
        
        CloseableHttpResponse response = null;
        
        try {
            // 执行请求
            response = httpClient.execute(httpGet);
            // 获取响应实体
            HttpEntity entity = response.getEntity();
            // 获取响应信息
            msg = EntityUtils.toString(entity, "UTF-8");
        } catch (ClientProtocolException e) {
            System.err.println("协议错误");
            e.printStackTrace();
        } catch (ParseException e) {
            System.err.println("解析错误");
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("IO错误");
            e.printStackTrace();
        } finally {
            if (null != response) {
                try {
                    EntityUtils.consume(response.getEntity());
                    response.close();
                } catch (IOException e) {
                    System.err.println("释放链接错误");
                    e.printStackTrace();
                }
            }
        }
        
        return msg;
    }
    
    public static void main(String[] args) {
        
        System.out.println(httpGet("http://www.baidu.com", 6000));
        
    }
    
}

至此,本节完毕,下一节记录【连接池的配置】

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,881评论 18 139
  • 第一章 Nginx简介 Nginx是什么 没有听过Nginx?那么一定听过它的“同行”Apache吧!Ngi...
    JokerW阅读 32,771评论 24 1,002
  • 本来是个简单工具的使用,没必要写什么博客的,但是StartUML有几个地方在画图的时候和别的工具(rose)不太一...
    千山万水迷了鹿阅读 4,091评论 0 1
  • 《风雨中的菊花》阅读题 风雨中的菊花 午后的天灰蒙蒙的,乌云压得很低,似乎要下雨。 多尔先生情绪很低落,他最烦在这...
    躲进小楼看灯火阅读 11,365评论 0 0
  • (写在感恩节) 夜晚三点半的闹钟响得实兀 黑夜倦曲在冰凉的马路 对楼的窗户闪耀着灯光 谁家婴孩半夜啼哭 星星眨着节...
    山上人家123阅读 222评论 5 13