我们是否应该在JestHttpClient响应弹性搜索后关闭连接

时间:2016-03-17 20:38:14

标签: java apache-httpclient-4.x jest

这是关于代码的 https://github.com/searchbox-io/Jest/blob/master/jest/src/main/java/io/searchbox/client/http/JestHttpClient.java

在此代码段中

    if [ $# -eq 0 ]
        then
                echo "No filename has been provided. Please enter a filename to restore!"
                exit 1
fi
echo You have entered $1
echo Looking for $1 in the list of items deleted by safe_rm...
restoredfile=$(grep ^$1 $HOME/.restore.info)
echo $restoredfile

我们收到回复之后,我们不应该做像

这样的事情
public <T extends JestResult> T execute(Action<T> clientRequest) throws IOException {
    HttpUriRequest request = prepareRequest(clientRequest);
    HttpResponse response = httpClient.execute(request);

    return deserializeResponse(response, request, clientRequest);
}

private <T extends JestResult> T deserializeResponse(HttpResponse response, Action<T> clientRequest) throws IOException {
    StatusLine statusLine = response.getStatusLine();
    return clientRequest.createNewElasticSearchResult(
            response.getEntity() == null ? null : EntityUtils.toString(response.getEntity()),
            statusLine.getStatusCode(),
            statusLine.getReasonPhrase(),
            gson
    );
}

这个特定的堆栈溢出线程HttpClient 4.0.1 - how to release connection?提到了使用

来使用响应实体
response.close()

只需要EntityUtils.consume(HttpEntity) 就足够了吗?

1 个答案:

答案 0 :(得分:1)

如果成功完成,

EntityUtils.toString(response.getEntity())就足够了。例如,如果抛出UnsupportedEncodingException,则toString将不会读取响应,并且将阻止连接。我的建议是在EntityUtils.consume(HttpEntity)块中调用finally以防止挂起连接。