2015-01-10 68 views
0

我使用很多http连接与Apache HttpClient(org.apache.httpcomponents 4.3.6)来测试服务器,并且我无法强制连接关闭,即使在另一个线程中在10秒钟后计划HttpConnectionManagerhttpClient.getConnectionManager().shutdown();时也是如此。如何强制Apache HttpClient/HttpConnection绝对关闭tcp连接?

httpClient.close()也没有帮助。

连接可以持续几分钟甚至几小时。

我已经定制SocketConfig尝试,这也没有帮助:

SocketConfig socketConfig = SocketConfig.custom() 
       .setSoKeepAlive(false) 
       .setSoLinger(5) 
       .setSoReuseAddress(true) 
       .setSoTimeout(5000) 
       .setTcpNoDelay(true).build(); 

的方式,我取的内容:

HttpUriRequest request = new HttpGet(url); 
    HttpResponse response = httpClient.execute(request); 

    try (InputStream in = response.getEntity().getContent()) { 
     String result = IOUtils.toString(in, StandardCharsets.UTF_8); 
     httpClient.close(); 
     return result; 
    } 

的方式我建立HTTP客户端:

SocketConfig socketConfig = SocketConfig.custom() 
      .setSoKeepAlive(false) 
      .setSoLinger(configuration.getInt("proxy.list.socket.so.linger")) 
      .setSoReuseAddress(true) 
      .setSoTimeout(configuration.getInt("proxy.list.socket.so.timeout")) 
      .setTcpNoDelay(true).build(); 

    HttpClientBuilder builder = HttpClientBuilder.create(); 
    builder.disableAutomaticRetries(); 
    builder.disableContentCompression(); 
    builder.disableCookieManagement(); 
    builder.disableRedirectHandling(); 
    builder.setConnectionReuseStrategy(new NoConnectionReuseStrategy()); 
    builder.setDefaultSocketConfig(socketConfig); 

我的关机原型之一:

 shutdownExecutor.schedule(() -> { 
      httpClient.getConnectionManager().closeExpiredConnections(); 
      httpClient.getConnectionManager().closeIdleConnections(1, TimeUnit.SECONDS); 
      httpClient.getConnectionManager().shutdown(); 

      httpClient.notifyAll(); 
      try { 
       httpClient.close(); 
      } catch (IOException ex) { 

      } 

     }, configuration.getInt("proxy.test.forced.timeout.seconds"), TimeUnit.SECONDS); 

     String content = HttpContentFetcher.getAndCloseClient(url, httpClient); 
+0

你可以发布一个最小样本?你如何试图关闭连接,你为什么说它没有效果? – Raffaele

+0

@Raffaele它在阅读反应上发挥作用。粘贴的细节。其实我很确定我已经达到了暂停,但长度约为300秒,而不是我想要的10秒。 –

+0

在代码中使用套接字逗留并期望套接字在同一时间立即关闭是有点奇怪的。 – oleg

回答

0

RequestConfig已帮助。现在看起来所有的连接都在指定的限制内被丢弃。

 RequestConfig config= RequestConfig.custom() 
       .setCircularRedirectsAllowed(false) 
       .setConnectionRequestTimeout(4000) 
       .setConnectTimeout(4000) 
       .setMaxRedirects(0) 
       .setRedirectsEnabled(false) 
       .setSocketTimeout(4000) 
       .setStaleConnectionCheckEnabled(true).build(); 
     request.setConfig(config);