发布于 2026-01-06 1 阅读
0

在 Node.js DEV 的全球展示挑战赛中启用 HTTPS keepAlive,由 Mux 呈现:展示你的项目!

在 Node.js 中启用 HTTPS keepAlive

由 Mux 赞助的 DEV 全球展示挑战赛:展示你的项目!

我也不知道为什么现在才知道这件事,但亡羊补牢,为时未晚:keepAliveNode.js 默认情况下未启用 HTTPS,这对网络密集型应用程序的性能有严重影响。

为了说明其影响,假设您的服务器托管在 [服务器地址],us-central1并且它与 [服务地址] 上的服务通信us-east1,仅网络延迟就约为 20 毫秒。由于 TCP 握手是一个包含 3 个数据包的过程,这意味着仅建立 TLS 握手就需要大约 60 毫秒的时间。

你可以用一个简单的脚本来测试:

const got = require('got');

const main = async () => {
  const response0 = await got('https://posthog.com/');

  console.log(response0.timings.phases);

  const response1 = await got('https://posthog.com/');

  console.log(response1.timings.phases);
};

main();
Enter fullscreen mode Exit fullscreen mode

在这种情况下,上述操作将产生以下结果:

{
  wait: 1,
  dns: 20,
  tcp: 72,
  tls: 74,
  request: 0,
  firstByte: 79,
  download: 222,
  total: 468
}
{
  wait: 0,
  dns: 1,
  tcp: 67,
  tls: 69,
  request: 1,
  firstByte: 73,
  download: 234,
  total: 445
}
Enter fullscreen mode Exit fullscreen mode

但是,total如果我们启用以下功能,请注意时间keepAlive

const got = require('got');
const https = require('https');

https.globalAgent = new https.Agent({ keepAlive:true });

const main = async () => {
  const response0 = await got('https://posthog.com/');

  console.log(response0.timings.phases);

  const response1 = await got('https://posthog.com/');

  console.log(response1.timings.phases);
};

main();
Enter fullscreen mode Exit fullscreen mode
{
  wait: 1,
  dns: 27,
  tcp: 77,
  tls: 75,
  request: 0,
  firstByte: 75,
  download: 220,
  total: 475
}
{
  wait: 0,
  dns: 0,
  tcp: 0,
  tls: 0,
  request: 0,
  firstByte: 77,
  download: 83,
  total: 160
}
Enter fullscreen mode Exit fullscreen mode

第二个请求比第一个请求快 70%!

如果你的应用程序依赖于大量的 HTTPS 调用,那么仅仅启用 HTTPS 功能keepAlive就能显著提升性能。

文章来源:https://dev.to/gajus/enable-https-keepalive-in-nodejs-2ecn