2014-04-14 86 views
2

我試圖使用HttpClient的重用和我有麻煩破譯1.1.5. Ensuring release of low level resources意義。HttpClient的連接與版本4.3.x

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

關閉內容流:(保持底層連接活着)

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

回答

1

一般而言,一旦你與實體做要放棄它,從而使系統資源不與不再有意義的對象捆綁起來。在我看來,這裏唯一的區別就是使用。關於基本面的那一章基本上就是描述這一點。但是,如果您實施它,請確保只在需要時才使用資源。低層次的資源是在實體InputStream中,高層次資源的連接。如果您正在實現的東西,並不需要閱讀完整的InputStream以作出決定,例如,剛剛結束的響應和清理會爲您有效地進行處理。

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 

在endof可運行的,客戶端只得到釋放回連接池,你不要擔心資源或清理。

使用,在末尾,則擴展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

相關問題