簡體   English   中英

使用 4.3.x 重用 HttpClient 連接

[英]HttpClient connection reusing with 4.3.x

我正在嘗試使用 HttpClient 並且無法解讀1.1.5的含義 確保釋放低級資源

這些是如何解釋關閉內容流關閉響應的?

關閉內容流:(保持底層連接處於活動狀態)

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();
}

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

在可運行結束時,客戶端剛剛被釋放回 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();

更多細節在這里

一般來說,一旦你完成了你想要丟棄的實體,這樣系統資源就不會被不再有意義的對象所束縛。 在我看來,這里唯一的區別是使用。 關於基礎的那一章基本上就是在描述這一點。 無論您如何實施它,請確保僅在需要時使用資源。 低層資源是實體中的InputStream,高層資源是連接。 例如,如果您正在實施不需要讀取完整 InputStream 來做出決定的內容,只需終止響應即可有效地為您處理清理工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM