2016-12-27 72 views
0

我写一个使用不同的API用于不同目的的多线程REST客户端,让我使用这些请求的HttpClient的,其不同的方法(GET,PUT,POST)高效的方式

主题1:

DefaultHttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost(url); 
httpclient.execute(httppost); 


methodThatNeedsHttpClient(httpclient); 


public void methodThatNeedsHttpClient(HttpClient client) { 
//perform other GET/POST/PUT requests 
} 

线程2:

DefaultHttpClient httpclient2 = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost(url); 
httpclient2.execute(httppost); 
// Other methods 

,我读了管理httpConnections我应该使用一个连接管理器。我在客户端的4.5版上,应该使用哪个连接管理器?连接管理器如何确保连接不泄漏并被有效使用?

我尝试以下实现:

PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager(); 
     connectionManager.setMaxTotal(5); 
// Perform REST operations 

client.getConnectionManager().shutdown(); 

但我不知道如何连接池中管理,对多线程系统,并连接管理器中的每一个线程被初始化?

回答

0

在大多数情况下,连接池应该是共享的,可由所有httpClient实例访问。

当创建HttpClient的,

CloseableHttpClient httpClient = HttpClients.custom() 
       .setConnectionManager(connectionManager) 
       .setConnectionManagerShared(true) 
       .build(); 

,这将释放连接回池中,

EntityUtils.consume(httpResponse.getEntity()); 

尽管将关闭连接,

httpResponse.close(); 
httpClient.close(); 

因为我们有setConnectionManagerShared(true)httpClient.close()不会分流连接池。