java中使用HttpClient的连接池

发布于 2024-10-15 06:06:16 字数 1436 浏览 6 评论 0 原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

逆流 2024-10-22 06:06:16

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

首先,由于您正在处理同一台服务器,因此建议使用单个 HTTP 客户端来执行您的请求。在 PoolingHttpClientConnectionManager 的帮助下,您的客户端可用于同时执行多个请求。官方多线程请求执行的例子可以参见

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

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

I have spent recent days working on this so just want to share some "everyone-known" knowledges with you.

First, as you are dealing with the same server, it is recommended to use a single HTTP client to execute your requests. With the help of PoolingHttpClientConnectionManager, your client can be used to execute multiple requests concurrently. The official example of multithreaded request execution can be found here.

Secondly, HTTP/1.1 (and enhanced versions of HTTP/1.0) allows HTTP clients to keep the connections open after transactions complete so that it can be reused for future requests. This is often refered as Persistent Connection.

Also for the purpose of reusing client for multiple requests, the response header from a server often include an attribute call Keep-Alive that contain the time current connection will be kept alive. Besides that, Apache Http Client also provides you an interface ConnectionKeepAliveStrategyto customize your own policy for reusing connection.

清秋悲枫 2024-10-22 06:06:16

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

PoolingClientConnectionManager is Deprecated now . from (4.3 version) use PoolingHttpClientConnectionManager.

原来是傀儡 2024-10-22 06:06:16

[假设 Java 和 Apache 的 HttpClient]

使用 ThreadSafeClientConnManager。将单个全局实例传递给每个 HttpClient 实例的构造函数。我认为汇集 HttpClient 本身没有任何意义。

[assuming Java, and Apache's HttpClient]

Use a ThreadSafeClientConnManager. Pass a single global instance to the constructor of every HttpClient instance. I don't think there's any point in pooling the HttpClients themselves.

新雨望断虹 2024-10-22 06:06:16

ThreadSafeClientConnManager 现已弃用,请使用 PoolingClientConnectionManager 相反。

ThreadSafeClientConnManager is deprecated now, use PoolingClientConnectionManager instead.

清晨说晚安 2024-10-22 06:06:16

对于 HttpClient 4x:

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

连接按路线汇集。对经理已经指定的路线的请求
池中有可用的持久连接将通过租用连接来提供服务
池而不是创建一个全新的连接。

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

For HttpClient 4x:

ThreadSafeClientConnManager ... manages a pool of client
connections
and is able to service connection requests from multiple execution threads.

Connections are pooled on a per route basis. A request for a route for which the manager already
has a persistent connection available in the pool will be serviced by leasing a connection from
the pool
rather than creating a brand new connection.

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

风渺 2024-10-22 06:06:16

这是不需要身份验证的 Apache HttpClient 4.3 连接池的示例:

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

This is an example of an Apache HttpClient 4.3 pool of connections which do not require authentication:

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
说谎友 2024-10-22 06:06:16

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

HttpClient has already have a connection pool.So you do not need to create it. Just use it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文