【发布时间】:2017-05-02 04:50:35
【问题描述】:
我正在使用 httpcomponents 来执行 http 请求。我已将connectionRequestTimeout、connectTimeout 和socketTimeout 设置为同一时间(例如8000ms)。系统处于高并发状态,大部分时间运行良好,但有些请求花费秒数,与每分钟超时时间(~8000ms)相同。这是代码sn-p:
RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(TIMEOUT).setConnectTimeout(TIMEOUT).setSocketTimeout(TIMEOUT).build();
CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
HttpUriRequest request = null;
switch (method) {
case GET:
String getUrl = url;
if (null != paramData) {
getUrl += "?" + paramData;
}
request = new HttpGet(getUrl);
break;
case POST:
...
default:
...
}
CloseableHttpResponse response = null;
try {
long start = System.currentTimeMillis();
response = client.execute(request);
long time = System.currentTimeMillis() - start;
// ***************************
// Sometime the log shows the cost is a few milliseconds more than TIMEOUT,
// but it does not throw any timeout exception and the response is fine.
// ***************************
LOG.debug("cost {}ms", time);
int resultCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
String resultJson = EntityUtils.toString(entity, UTF_8);
if (HttpStatus.SC_OK == resultCode) {
...
}
} catch (Exception e) {
...
} finally {
//abort the request
if (null != request && !request.isAborted()) {
request.abort();
}
//close the connection
HttpClientUtils.closeQuietly(client);
HttpClientUtils.closeQuietly(response);
}
httpcomponents的版本是4.5.2,jdk是openjdk 1.8.0_92。
此外,我应该使用CloseableHttpClient 作为单例以获得更好的性能吗?
【问题讨论】:
-
这个问题已经通过将
CloseableHttpClient设置为单例来解决。我认为new一个客户端对于每个 http 请求都是非常昂贵的。顺便说一句,如果我们想重用客户端,我们不应该closeCloseableHttpClient。 -
您能接受下面的答案吗?它将帮助其他人解决他们的类似问题。谢谢