我在这里读到 EntityUtils.consume(httpEntity)
将导致将连接释放回连接池,但是当我查看源代码时,我不明白这是怎么发生的。有人能告诉我代码的哪一部分吗 EntityUtils.consume(httpEntity)
或者 EntityUtils.toString(httpEntity)
在使用elastic search rest客户端(org.elasticsearch.client.restclient-低级rest客户端)时释放连接,如下所示:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/master/java-rest-low-usage-responses.html?
如果存在sockettimeoutexception并且我不使用httpentity,连接会发生什么情况?
1条答案
按热度按时间s8vozzvw1#
客户端关闭并释放到池的连接(步骤)
EntityUtils.consume
&EntityUtils.toString
>第一个会的close()
这个instream
如果它完全消耗实体。第二个总会打电话来instream.close()
在它的finally子句中。instream
是指定给inputstream变量的名称。instream
.close()
>对于本例,实现InputStream
是一个ContentInputStream
. 这个close()
方法强制ContentInputStream
通过代码片段中显示的循环机制读取到其结束。以下对此流的调用将导致
EOF
例外。(spot1) [HttpConn1] -- ThreadA
(spot2) [HttpConn2] -- ThreadB
(spot3) [HttpConn3] -- ThreadC
```
ThreadA
完成了它的工作并关闭了它的连接。这个Pool
会注意到这一点时的状态PoolEntry
已关闭。不同的PoolEntry
实现将检查这是不同的方式,其中之一是获得EOF
尝试从流读取时出现异常。其他实现可以有不同的机制来检查资源是否关闭。如果PoolEntry
告知他的资源已关闭/无效,则Pool
会回收这个地方。这里有两个选项:a) 擦除并创建。
b) 恢复。
“释放连接回来”可以翻译成“现在又有了一个可用的地点/资源”。池现在可以连接到
ThreadZ
:public static void consume(final HttpEntity entity) throws IOException
{
if (entity == null)
return;
}
public static String toString(final HttpEntity entity, final Charset defaultCharset)
throws IOException, ParseException
{
Args.notNull(entity, "Entity");
InputStream instream = entity.getContent();
if (instream == null) {
return null;
}
try {
Args.check(entity.getContentLength() <= Integer.MAX_VALUE,
"HTTP entity too large to be buffered in memory");
int i = (int)entity.getContentLength();
if (i < 0) {
i = 4096;
}
Charset charset = null;
try {
ContentType contentType = ContentType.getOrDefault(entity);
charset = contentType.getCharset();
} catch (UnsupportedCharsetException ex) {
throw new UnsupportedEncodingException(ex.getMessage());
}
if (charset == null) {
charset = defaultCharset;
}
if (charset == null) {
charset = HTTP.DEF_CONTENT_CHARSET;
}
Reader reader = new InputStreamReader(instream, charset);
CharArrayBuffer buffer = new CharArrayBuffer(i);
char[] tmp = new char[1024];
int l;
while((l = reader.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
return buffer.toString();
} finally {
instream.close(); // <--- connection release
}
}
void tryConsume()
{
try
{
//...
EntityUtils.consume(httpEntity);
//...
}
catch (IOException)
{
//SocketTimeoutException happened. Log the error,etc
// (Close resources here...)
}
finally
{
//...Or maybe include a finally clause and close them here, if you wish
// them to be closed regardless of success/failure.
if (httpEntity!=null)
{
InputStream instream = httpEntity.getContent();
if (instream != null)
instream.close(); /* <-- connection release. when checking this
spot, the pool will get (f.e) an EOF
exception. This will lead to replacing this
resource with a fresh new connection and
setting the spot status as avaliable. */
}
}
}