2016-06-11 75 views
1

我尝试了两个代码。我只是同时从两个浏览器访问这些程序。为什么在Node.js上表示“连续”处理http请求?

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

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

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

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

你能教我为什么表达这样的行为?同时处理一些http请求的唯一解决方案就是使用Cluster?

的Sample1

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!'); 
}); 

的Sample1的输出

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 
+0

Sample2似乎与Sample1完全相同的代码? – DAXaholic

+0

非常抱歉!我修好了它。 – ykensuke9

+0

增加超时时你会得到不同的结果吗? – eenagy

回答

3

这可能是因为你的浏览器中所描述的here

我只是样本1和curl测试它通过使用

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

射击5个请求,我看到他们同时运行 - 看到GIF 。
所以我不认为express是序列化您的请求,但你的客户端。

enter image description here

顺便说一句:以我输出有表示Date.now()每个日志行附加的第三列作为我的初始猜测是这是因为缓冲的输出日志。

+0

谢谢!我完全误解了,你的回答真的很清楚! – ykensuke9

+0

Upvote额外的努力和清晰的答案。 –