【问题标题】:Efficient way of using apache HttpClient使用 apache HttpClient 的有效方法
【发布时间】:2018-07-01 16:11:24
【问题描述】:

我正在编写一个多线程 REST 客户端,它使用不同的 API 来实现不同的目的,为了发出这些请求,我使用了具有不同方法(GET、PUT、POST)的 HttpClient

线程 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();

但我不确定池中的连接是如何管理的,对于多线程系统,连接管理器是否在每个线程中都进行了初始化?

【问题讨论】:

    标签: performance apache-httpclient-4.x


    【解决方案1】:

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

    创建httpClient时,

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

    这将释放连接回池,

    EntityUtils.consume(httpResponse.getEntity());
    

    虽然会关闭连接,

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

    由于我们有setConnectionManagerShared(true)httpClient.close() 不会关闭连接池。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多