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));
        
    }
    
}

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 162,825评论 4 377
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,887评论 2 308
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 112,425评论 0 255
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,801评论 0 224
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 53,252评论 3 299
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 41,089评论 1 226
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,216评论 2 322
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 31,005评论 0 215
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,747评论 1 250
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,883评论 2 255
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,354评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,694评论 3 265
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,406评论 3 246
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,222评论 0 9
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,996评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 36,242评论 2 287
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 36,017评论 2 281

推荐阅读更多精彩内容

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