繁体   English   中英

如何强制Apache HttpClient / HttpConnection绝对关闭tcp连接?

[英]How to force Apache HttpClient / HttpConnection to absolutely close tcp connection?

我使用许多与Apache HttpClient(org.apache.httpcomponents 4.3.6)建立的http连接来测试服务器,即使将HttpConnectionManager调度到httpClient.getConnectionManager().shutdown();也无法强制关闭连接httpClient.getConnectionManager().shutdown(); 在另一个线程10秒后。

httpClient.close()也无济于事。

连接可能持续数分钟甚至数小时。

我尝试了自定义SocketConfig ,这也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);

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM