首页 > 解决方案 > 从 nodejs 向第三方 API 请求的性能瓶颈

问题描述

我在我的 nodejs 应用程序中使用第三方 API。

首先,当我这样做的时候hey -c 20 -z 30s -cpus 1 http://api_url.com,我开始了Requests/sec: 57

原始 API 响应约为 275000 个符号 (UTF8)(api 响应为JSON)。

我的应用程序的简化示例:

const req = () => {
  const url = 'http://api_url.com';
  return new Promise((resolve, reject) => {
    const r = http.get(
      url,
      (res) => {
        res.setEncoding('utf8');
        let rawData = '';
        res.on('data', chunk => {
          rawData += chunk;
        });

        res.on('end', () => {
          const parsedData = JSON.parse(rawData);
          resolve(parsedData);
        });
      });
  });
}

koaRouter.get("/", async (ctx, next) => {
  ctx.type = "html";
  const data = await req();
  ctx.body = data;
});

app.use(koaRouter.routes()).use(koaRouter.allowedMethods());

app.listen(9000, () => {
  console.log("\n--------- Started ---------");
});

如果我跑步,hey -c 20 -z 30s -cpus 1 http://localhost:9000那么我会得到大约Requests/sec: 15

我认为这与大型 API 响应有关,因为如果我在获取第一个块后停止每个请求:

res.on('data', chunk => {
  resolve('end');
  r.abort();
});

的运行hey ....提供了关于Requests/sec: 50

我知道我可以在集群模式下运行 nodejs 应用程序,但是Requests/sec在我的情况下是否可以增加(如果在fork模式下运行)?

标签: node.jsperformanceapi

解决方案


推荐阅读