如何在 PoolingHttpClientConnectionManager 中设置 setMaxPerRoute?

How to set setMaxPerRoute in PoolingHttpClientConnectionManager?

PoolingHttpClientConnectionManager 我想在其中设置每条路线的最大连接数。我用下一种方式来做:

poolingHttpClientConnectionManager.setDefaultMaxPerRoute(5);
poolingHttpClientConnectionManager.setMaxPerRoute(new HttpRoute(HttpHost.create(url)), 3);

例如我的 urlhttps://repo.maven.apache.org/maven2。 所以我有每条路线 5 的默认最大值和每个特定 url 的 3。然后如果我打电话给

poolingHttpClientConnectionManager.getStats(new HttpRoute(HttpHost.create(url))); 

我收到 PoolStatsmax = 3 的结果,所以现在一切正常。

但是当我使用池连接管理器创建客户端并调用相同的客户端时 url 我可以在日志中看到:

PoolingHttpClientConnectionManager - Connection leased: [id: 0][route: {s}->https://repo.maven.apache.org:443][total kept alive: 0; route allocated: 1 of 5; total allocated: 1 of 200]

正如我所见,它仍然使用 5 个连接作为该示例的最大值 url。 所以我的问题是如何设置每条路由的最大连接数以使其正常工作?

好的,我已经设法用下一个代码修复它:

// code to create HttpRoute the same as in apache library
private HttpRoute getHttpRouteForUrl(String url) throws URISyntaxException
{
    URI uri = new URI(url);
    boolean secure = uri.getScheme().equalsIgnoreCase("https");
    int port = uri.getPort();
    if (uri.getPort() > 0)
    {
        port = uri.getPort();
    }
    else if (uri.getScheme().equalsIgnoreCase("https"))
    {
        port = 443;
    }
    else if (uri.getScheme().equalsIgnoreCase("http"))
    {
        port = 80;
    }
    else
    {
        LOGGER.warn("Unknown port of uri %s", repository);
    }
    HttpHost httpHost = new HttpHost(uri.getHost(), port, uri.getScheme());
    // TODO check whether we need this InetAddress as second param
    return new HttpRoute(httpHost, null, secure);
}

如果我们将此 HttpRoute 用于 setMaxPerRoute,一切都会按预期进行。