HttpClient连接重用4.3.x

时间:2014-04-14 16:48:52

标签: java httpclient

我正在尝试使用HttpClient,但我无法破译1.1.5. Ensuring release of low level resources的含义。

是否关闭内容流以及关闭响应的解释是什么?

关闭内容流:(保持基础连接处于活动状态)

CloseableHttpClient httpclient = HttpClients.createDefault();
try {
    HttpGet httpget = new HttpGet("http://localhost/");

    // do multiple times on the same connection
    for (...) {
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            try {
                // do something useful
            } finally {
                EntityUtils.consume(entity);    // <-- ensures reuse
            }
        }
    }
} finally {
    httpclient.close();
}

关闭回复:(立即关闭并放弃连接)

CloseableHttpClient httpclient = HttpClients.createDefault();
try {
    HttpGet httpget = new HttpGet("http://localhost/");

    // do multiple times on different connections
    for (...) {
        ClosableHttpResponse response = httpclient.execute(httpget);
        try {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                // do something useful
            }
        } finally {
            response.close();    // <-- ensures reconnect
        }
    }
} finally {
    httpclient.close();
}

2 个答案:

答案 0 :(得分:1)

通常,一旦您完成了要放弃它的实体,系统资源就不会与不再有意义的对象捆绑在一起。在我看来,这里唯一的区别是使用。关于基本原则的那一章基本上是在描述这一点。但是,如果您实现它,请确保只在您需要时才使用资源。低级资源是实体中的InputStream,高级资源是连接。如果你正在实现一些不需要读取完整InputStream的东西来做出决定,例如,只需终止响应,就会有效地处理清理工作。

答案 1 :(得分:1)

entityUtils.consume为你关闭流......

if (entity.isStreaming()) {
    final InputStream instream = entity.getContent();
    if (instream != null) {
        instream.close();
    }
}

您只需将您的客户“释放”回游泳池......

然后,你应该将你的HttpClient包装在一个可运行的......

public void run() {
    handler.sendMessage(Message.obtain(handler, HttpConnection.DID_START));
    CloseableHttpClient httpClient = HttpClients.custom()
            .setConnectionManager(YourConnectionMgr.getInstance())
            .addInterceptorLast(new HttpRequestInterceptor() {
                public void process(
                    final HttpRequest request, 
                    final HttpContext context) throws HttpException, IOException { 
                    }
                })
                .build();
 }  //end runnable

在runnable结束时,客户端刚刚被释放回ConnectionPool,您不必担心资源或清理。

使用扩展PoolingClientConnectionManager

的经理
newInstance =  new MyConnectionManager(schemeRegistry);
     instance.setMaxTotal(15);
     instance.setDefaultMaxPerRoute(15);
     HttpHost localhost = new HttpHost("api.parse.com", 443);
     instance.setMaxPerRoute(new HttpRoute(localhost), 10);

然后在最后,我认为你确实需要关闭游泳池。

YourConnectionMgr.getInstance().shutdown();
YourConnectionMgr.reset();

更多详情here