PoolingHttpClientConnectionManager 不重新使用现有的空闲连接

PoolingHttpClientConnectionManager not re-using existing Idle connection

我正在使用 Apache PoolingHttpClientConnectionManager 创建连接池。但是,我在日志中看到未使用现有的空闲连接,而是创建了一个新连接。下面是代码

PoolingHttpClientConnectionManager connManager = connManager = new PoolingHttpClientConnectionManager();
connManager.setMaxTotal(4);
    connManager.setDefaultMaxPerRoute(4);

//Creating CloseableHttpClient with a default keep alive of 2 minutes
    CloseableHttpClient  client = HttpClients.custom()
            .setConnectionManager(connManager)
            .setKeepAliveStrategy(new KeepAliveStrategy(keepAlive))
            .build();


//Sending 1st request
String xml="<xml data>";
HttpPost post = new HttpPost("<URL>");
    HttpEntity entity = new ByteArrayEntity(xml.getBytes("UTF-8"));
    post.setEntity(entity);
    HttpResponse  response =client.execute(post);
    String result = EntityUtils.toString(response.getEntity());
    EntityUtils.consume(response.getEntity());

收到响应后,PoolStats 表示可用连接总数为 1

现在我在 5 秒后再次发出相同的请求,在收到响应后 PoolStats 指出 可用连接总数为 2

以下代码用于 PoolStats

 PoolStats stats = connManager.getTotalStats();
    System.out.println("Total Connections Available : "+stats.getAvailable());

My Question here is Since after the First Request-response there was already a Connection in the pool so why did it create one more connection. Why it did not use the existing conenction?

问题是因为我在这里使用 SSL,所以默认情况下不允许 SSL 上下文共享相同的连接。这就是它为每个请求创建另一个连接的原因。创建自定义 UserTokenHandler 并将其分配给连接管理器的解决方案。

UserTokenHandler userTokenHandler = new UserTokenHandler() {

        @Override
        public Object getUserToken(final HttpContext context) {
            return context.getAttribute("my-token");
        }

    };

client = HttpClients.custom()
            .setConnectionManager(connManager)
            .setUserTokenHandler(userTokenHandler)
            .setKeepAliveStrategy(new KeepAliveStrategy(keepAlive))
            .build();