为什么在使用池连接管理器时我的 HTTPClient 运行 没有连接?

Why is my HTTPClient running out of connections when using pooled connection manager?

我正在使用 Apache HttpComponents 4.5.1。在 Scala 项目中,但是 Scala 不太可能成为我的问题。这是一个 JUnit 4 风格的测试。

@Test def closableHttpClientWithPoolingCmTest{
  val poolingHttpConnectionManager: PoolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager()
  poolingHttpConnectionManager setMaxTotal (12)
  poolingHttpConnectionManager setDefaultMaxPerRoute (8)
  def client = HttpClients custom () setConnectionManager  (poolingHttpConnectionManager) build ()
  for (i  <- 0 to 12 ){
    def response = client.execute(new HttpGet("http://www.yahoo.com"));
    EntityUtils.consume(response.getEntity)
    response.close();
  }
}

此测试挂起,因为我们 运行 连接中断。我错过了什么?我使用实体并关闭响应。除了 response 之外,我还需要关闭其他任何东西吗? 请帮忙。

您的客户端定义应该是 val 而不是 def

每次调用 client 时都会计算

def,从而为每次调用创建一个新池。取而代之的是 val 您的游泳池将构建一次并重复使用。

def client = HttpClients custom () setConnectionManager (poolingHttpConnectionManager) build ()

应该变成

val client = HttpClients custom () setConnectionManager (poolingHttpConnectionManager) build ()