HttpsServer 使用 curl 导致 100% CPU 负载

Mat*_*aun 4 java performance https curl server

我围绕 Java 的HttpsServer.

我安装了HttpHandler一个用短信回复请求的程序:

return exchange -> {
    try {
        OutputStream responseBodyStream = exchange.getResponseBody();

        byte[] response = "Trouble with HTTPS and curl\n"
                .getBytes(StandardCharsets.UTF_8);

        exchange.getResponseHeaders().set("Content-Type", "text/plain");

        exchange.sendResponseHeaders(200, response.length);

        responseBodyStream.write(response);

        responseBodyStream.close();

        // Note that exchange.close() also closes the exchange's input stream
        // and output stream

    } catch (Exception e) {
        log.warn("Could not handle request", e);
    }
};
Run Code Online (Sandbox Code Playgroud)

当使用 curl 连接到服务器时,服务器响应,但 Java 进程继续使用整个核心,从而使服务器无响应。

正是这一行触发了这个问题:

responseBodyStream.close();
Run Code Online (Sandbox Code Playgroud)

如果我们删除该行,服务器将继续工作。

文档

为了正确终止每个交换,输出流必须关闭,即使没有发送响应正文。

我创建了一个项目来重现该问题。

到目前为止,我发现了一些潜在的线索:

  • 只有在使用 curl 连接到服务器时才会出现高 CPU 使用率。与 Firefox 连接时,CPU 使用率保持较低
  • 使用没有 TLS 的常规 HTTP 服务器时,curl 不会出现此问题
  • 使用Flight Recorder收集的数据表明SSLEngineImpl#writeRecord线程中HTTP-Dispatcher分配了大量对象

我在 Arch Linux 5.1.7 上使用 OpenJDK 12.0.1+12。curl 的版本是 7.65.1。

这是JDK中的错误吗?还是我用HttpsServer错了方法?

apa*_*gin 5

我也可以重现这个问题。
有一个无限循环SSLStreams.doClosure- 这绝对是一个 JDK 错误。

HttpsServer 在 JDK 10 中运行良好,但在 JDK 11 中开始循环。我想问题是 HttpsServer 实现尚未适应 JDK 11 中出现的 TLS v1.3 半关闭策略。

幸运的是,有一个解决方法。添加-Djdk.tls.acknowledgeCloseNotify=trueJVM选项。使用此选项 HttpsServer 将按预期工作。有关详细信息,请参阅JDK-8208526