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,915評論 18 139
  • 第一章 Nginx簡介 Nginx是什么 沒有聽過Nginx?那么一定聽過它的“同行”Apache吧!Ngi...
    JokerW閱讀 32,781評論 24 1,002
  • 本來是個簡單工具的使用,沒必要寫什么博客的,但是StartUML有幾個地方在畫圖的時候和別的工具(rose)不太一...
    千山萬水迷了鹿閱讀 4,096評論 0 1
  • 《風雨中的菊花》閱讀題 風雨中的菊花 午后的天灰蒙蒙的,烏云壓得很低,似乎要下雨。 多爾先生情緒很低落,他最煩在這...
    躲進小樓看燈火閱讀 11,388評論 0 0
  • (寫在感恩節) 夜晚三點半的鬧鐘響得實兀 黑夜倦曲在冰涼的馬路 對樓的窗戶閃耀著燈光 誰家嬰孩半夜啼哭 星星眨著節...
    山上人家123閱讀 222評論 5 13