使用HttpClient进行HTTP连接池

  • 如何使用HttpClient创建连接池?
  • 我必须经常连接到同一台服务器。 是否值得创建这样的游泳池?
  • 是否可以保持实时连接并将其用于各种请求,如果是,我该怎么办?

我正在使用Apache HTTP Client开发Java。

[假设Java和Apache的HttpClient]

使用ThreadSafeClientConnManager 。 将单个全局实例传递给每个HttpClient实例的构造函数。 我认为将HttpClients本身集中在一起并不存在任何意义。

PoolingClientConnectionManager现已弃用。 从(4.3版)开始使用PoolingHttpClientConnectionManager

现在不推荐使用ThreadSafeClientConnManager,而是使用PoolingClientConnectionManager 。

我最近几天都在研究这个问题,所以我想与大家分享一些“众所周知”的知识。

首先,在处理同一服务器时,建议使用单个HTTP客户端来执行请求。 在PoolingHttpClientConnectionManager的帮助下,您的客户端可用于同时执行多个请求。 可以在此处找到multithreading请求执行的官方示例。

其次,HTTP / 1.1(以及HTTP / 1.0的增强版本)允许HTTP客户端在事务完成后保持连接打开,以便可以在将来的请求中重用它。 这通常被称为持久连接

此外,为了将客户端重用于多个请求,来自服务器的响应头通常包括一个属性调用Keep-Alive ,其中包含当前连接将保持活动的时间。 除此之外,Apache Http Client还为您提供了一个接口ConnectionKeepAliveStrategy来定制您自己的重用连接策略。

对于HttpClient 4x:

ThreadSafeClientConnManager …管理客户端连接池,并能够为来自多个执行线程的连接请求提供服务。

连接以每个路由为基础进行池化 。 管理员已经在池中提供持久连接的路由请求将通过从池租用连接而不是创建全新连接来进行服务。

http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html

这是Apache HttpClient 4.3连接池的一个示例,它不需要身份validation:

 public class PoolOfHttpConnections{ static String[] urisToGet = {"http://www.site1.com", "http://www.site2.com"}; public static void main(String[] args) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); // create a thread for each link GetThread[] threads = new GetThread[urisToGet.length]; for (int i = 0; i < threads.length; i++) { HttpGet httpget = new HttpGet(urisToGet[i]); threads[i] = new GetThread(httpClient, httpget); } // start the threads for (int j = 0; j < threads.length; j++) { threads[j].start(); } // join the threads for (int j = 0; j < threads.length; j++) { threads[j].join(); } } //end main private static class GetThread extends Thread { private final CloseableHttpClient httpClient; private final HttpContext context; private final HttpGet httpget; public GetThread(CloseableHttpClient httpClient, HttpGet httpget) { this.httpClient = httpClient; this.context = HttpClientContext.create(); this.httpget = httpget; } @Override public void run() { try { CloseableHttpResponse response = httpClient.execute(httpget, context); try { HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); Date date = new Date(); System.out.println("Beginning*******************"); System.out.println(date.toString()); System.out.println("There are "+urisToGet.length+" threads running in parallel!"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } System.out.println(EntityUtils.toString(entity)); EntityUtils.consume(entity); } finally { response.close(); System.out.println("End*******************"); } } catch (ClientProtocolException ex) { // Handle protocol errors } catch (IOException ex) { // Handle I/O errors } } } /*end private class*/ }//end public class PoolOfHttpConnections 

HttpClient已经有了一个连接池。所以你不需要创建它。 只是使用它。