【问题标题】:Release apache http connection to pool when response is null响应为空时释放 apache http 连接到池
【发布时间】:2018-02-15 23:41:26
【问题描述】:

我们正在使用 apache http 客户端连接到外部帮助系统。我们正在使用 Hystrix 命令来执行 http 请求。 当这些请求需要更多时间来响应并且时间超过 Hystrix 超时时间时,Hystrix 将返回为 null 的回退。

由于它返回 null Http 响应,因此无法使用 EntityUtils 消费,因此连接不会返回到连接池。

我们已经尝试使用httpGet.releaseConnection。但它似乎不起作用。

当 http 请求的响应时间比预期时间长时,将连接释放回池的最佳方法是什么?

Hystrix 后退

@Override
protected CloseableHttpResponse getFallback() {
    logger.error(" Returning fallback");
    return null;
}

执行 REST 查询和处理结果的代码

CloseableHttpClient httpClient = //Get client from pool
HttpGet httpGet = new HttpGet(serverPath);
HystrixTestCommand testCommand = new HystrixTestCommand(httpClient, httpGet);
CloseableHttpResponse httpResponse = testCommand.execute();
if (httpResponse != null
        && httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
    //Consule entity
} else if (httpResponse != null 
        && httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
    //Consule entity
} else if(httpResponse == null){
    // When http request not responded within anticipated time
    httpGet.releaseConnection();
    logger.info("Release connection");
    return null;
}

【问题讨论】:

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


    【解决方案1】:

    HttpClient 会在请求执行过程中抛出任何异常或调用者中止请求时自动释放所有资源。您可以使用HttpGet#abort 来终止请求并确保取消分配与其相关的资源。

    【讨论】:

    • 中止后似乎正在释放连接。谢谢
    • 但是 releaseConnection 和 abort 方法有什么区别呢?他们所做的一切都重置了一些原子变量。实现如何依赖它们?
    • 就资源管理而言,它们几乎做同样的事情。然而,#abort 方法使请求对象处于无效(中止)状态,而 #releaseConnection 和 #reset 方法将请求重置为其初始状态,从而使其能够重用和重新执行。
    • 完美。现在很清楚了。再次感谢您的澄清。这些差异是否记录在某处?特别是在使用池时,调用 http 客户端的代码必须调用所有这些方法,以便将连接释放到池
    猜你喜欢
    • 2012-04-22
    • 1970-01-01
    • 2014-08-06
    • 2013-05-01
    • 2016-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-26
    相关资源
    最近更新 更多