gpt4 book ai didi

node.js - 为什么 Node.js 上的 Express 处理 http 请求 "serially"?

转载 作者:太空宇宙 更新时间:2023-11-03 22:52:28 25 4
gpt4 key购买 nike

我尝试了以下两个代码。我刚刚同时从两个浏览器访问了这些程序。

在Sample1中,res.send在所有处理之后执行,这是一般实现。我的意思是,这些“setTimeout”可以是数据库访问或类似的东西。

在 Sample2 中,首先执行 res.send,然后进行其余处理。

根据Sample1的输出,每个http请求都是串行处理的。因此,如果有人同时访问该网站,他们需要等待前面的每个人。起初,我认为原因是 Node.js 串行处理所有内容。但根据Sample2的结果我发现这是错误的理解。从结果来看,Node.js 可以同时处理一些函数,其中包括像 setTimeout 这样的非阻塞代码。

所以我不明白为什么express要这样实现。因此,我们需要像PM2一样使用Cluster来同时处理一些http请求。

你能告诉我为什么 Express 会有这样的行为吗?同时处理一些http请求的唯一解决方案就是使用集群?

示例1

var express = require('express');
var app = express();

app.get('/', function (req, res) {
var id = Math.floor(1000*Math.random())
console.log('0 - ' + id)
setTimeout(()=>{
console.log('1 - ' + id)
setTimeout(()=>{
console.log('2 - ' + id)
setTimeout(()=>{
console.log('3 - ' + id)
res.send('Hello World!');
}, 1000)
}, 1000)
}, 1000)
});

app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});

示例 1 的输出

0 - 957
1 - 957
2 - 957
3 - 957
0 - 447
1 - 447
2 - 447
3 - 447

示例2

var express = require('express');
var app = express();

app.get('/', function (req, res) {
res.send('Hello World!');
var id = Math.floor(1000*Math.random())
console.log('0 - ' + id)
setTimeout(()=>{
console.log('1 - ' + id)
setTimeout(()=>{
console.log('2 - ' + id)
setTimeout(()=>{
console.log('3 - ' + id)
}, 1000)
}, 1000)
}, 1000)
});

app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});

样本2的输出

0 - 902
0 - 742
1 - 902
1 - 742
2 - 902
2 - 742
3 - 902
3 - 742

最佳答案

这可能是因为您的浏览器问题,如所述 here

我刚刚使用 Sample1 和 curl 进行了测试

for i in $(seq 1 5); do curl localhost:3000/ & done  

触发 5 个请求,我看到它们同时运行 - 请参阅 GIF。
所以我不认为 express 正在序列化您的请求,而是您的客户端。

enter image description here

顺便说一句:在我的输出中,有一个额外的第三列,显示每个日志行的 Date.now() ,因为我最初的猜测是这是因为缓冲日志输出。

关于node.js - 为什么 Node.js 上的 Express 处理 http 请求 "serially"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37759762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com