node.js - 从 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
模式下运行)?
解决方案
推荐阅读
- azure - 尝试在突触上使用自定义库运行笔记本时,LIBRARY_MANAGEMENT_FAILED 的原因是什么?
- pytorch - 使用贝叶斯神经网络的学习后验作为先验,然后进行训练
- python - bs4 丢弃特定标签之前的所有 HTML
- sql - 如何强制 SSIS 将反斜杠读取为单个符号
- prolog - PROLOG 中的布尔值守卫
- html - 无效的 HTML5 输入模式 - 正则表达式
- terraform - 无法使用新的人工远程后端对 init 进行改造
- ruby - 如何在 RUBY 中将字符串“1000-2000”格式化为 10:00-20:00
- node.js - 如何在服务器和客户端上为 Mongoose 模式提供相同的 TypeScript 接口,以便直接从 JSON 中使用?
- amazon-web-services - 有没有办法使用浏览器而不是以编程方式授予 IAM 用户查看 DynamoDB 表的权限?