緊接上一節,本節記錄 【連接超時的配置】
工作中有這樣一個需求,要對上千臺的服務器進行更新測試,這是需要開幾百個線程做并發測試,每個線程中都有N次的Http請求,看服務器是否可以頂得住
。但是碰到一個問題,那就是訪問的過程中有些線程莫名其妙就不訪問了,觀察服務器端,并沒有請求進來。開始各種懷疑,是線程自己死掉了?還是Windows對每個進程有線程的限制?亦或者是HttpClient對總連接數量有限制?
最后經過每一步的測試和排查,確定問題在于兩方面:
-
httpClient
客戶端連接對象并沒有配置連接池,使用默認的連接池不能支持那么多的并發量。 - 沒有給每一次的連接設置超時時間
獲取連接超時
請求超時
響應超時
,如果沒有設置超時時間,連接可能會一直存在阻塞
,所以線程一直停在那里,其實線程并沒有死掉
。
也就是說,我們只需把上述兩個問題解決問題就迎刃而解了。本節先說連接超時時間的設置。
上代碼:
- 類
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));
}
}
至此,本節完畢,下一節記錄【連接池的配置】