当响应为空时释放 apache http 连接到池

Release apache http connection to pool when response is null

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

因为它是 returning null Http 响应,所以不能使用 EntityUtils 消耗,因此连接不会 returned 到连接池。

我们已经尝试使用 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;
}

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