【问题标题】:Apache HTTP client only two connections are possibleApache HTTP 客户端只有两个连接是可能的
【发布时间】:2014-10-01 09:07:36
【问题描述】:

我有以下代码来使用 Apache HTTP 客户端调用 REST API 方法。但是,使用上述客户端只能发送两个并行请求。 有没有设置最大连接数的参数?

     HttpPost post = new HttpPost(resourcePath);
            addPayloadJsonString(payload, post);//set a String Entity
            setAuthHeader(post);// set Authorization: Basic header
            try {
                return httpClient.execute(post);

            } catch (IOException e) {
                String errorMsg = "Error while executing POST statement";
                log.error(errorMsg, e);


  throw new RestClientException(errorMsg, e);
        }

我正在使用的罐子如下,

org.apache.httpcomponents.httpclient_4.3.5.jar
org.apache.httpcomponents.httpcore_4.3.2.jar

【问题讨论】:

    标签: apache rest http httpclient


    【解决方案1】:

    你可以用HttpClientConnectionManager配置HttpClient

    看看Pooling connection manager

    ClientConnectionPoolManager 维护一个HttpClientConnections 池,并且能够为来自多个执行线程的连接请求提供服务。连接按每条路由汇集。对管理器已经在池中可用的持久连接的路由的请求将通过从池中租用连接而不是创建全新的连接来提供服务。

    PoolingHttpClientConnectionManager 在每条路由的基础上和总计上维护最大连接限制。默认情况下,此实现将为每个给定路由创建不超过 2 个并发连接,并且总共不超过 20 个连接。对于许多实际应用程序而言,这些限制可能过于严格,尤其是当它们使用 HTTP 作为其服务的传输协议时。

    这个例子展示了如何调整连接池参数:

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    // Increase max total connection to 200
    cm.setMaxTotal(200);
    // Increase default max connection per route to 20
    cm.setDefaultMaxPerRoute(20);
    // Increase max connections for localhost:80 to 50
    HttpHost localhost = new HttpHost("locahost", 80);
    cm.setMaxPerRoute(new HttpRoute(localhost), 50);
    
    CloseableHttpClient httpClient = HttpClients.custom()
            .setConnectionManager(cm)
            .build();
    

    【讨论】:

    • 感谢您的回答。还有一个问题。如果使用池连接管理器,我们不必在执行 GET 或 POST 时关闭连接,如下所示,是吗? HttpPost post = new HttpPost(resourcePath);尝试 { 返回 httpClient.execute(post); } catch (IOException e) { //处理异常 }finally { post.releaseConnection(); }
    猜你喜欢
    • 2020-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-26
    • 1970-01-01
    • 2021-01-05
    • 2011-05-20
    • 2019-08-17
    相关资源
    最近更新 更多