为什么setTimeout会阻塞我的Node.js应用程序?

时间:2016-03-06 10:51:13

标签: javascript node.js asynchronous

使用此代码,Http服务器的典型节点js示例,我已经添加了5秒的延迟来模拟在其他地方发生的某些异步工作:

const http = require('http');

const hostname = '127.0.0.1';
const port = 8080;

http.createServer((req, res) => {
  setTimeout(()=>{
      res.writeHead(200, { 'Content-Type': 'text/plain' });
      res.end('Hello World\n');
  },5000);
}).listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

我期望的是,当我打开5个标签时,让我们说在打开每个标签之间延迟半秒,服务器应该"响应"对于每个选项卡或多或少的时间:

t=0s - I open first tab
t=0.5s - I open second tab
t=1s - I open third tab
...
t=5s - First tab stops loading, server has replied
t=5.5s - Second tab stops loading, server has replied
t=6s - Third tab stops loading, server has replied
t=6.5s - Fourth tab stops loading, server has replied
t=7s - Fifth tab stops loading, server has replied

但是,我看到的行为如下:

t=0s - I open first tab
t=0.5s - I open second tab
t=1s - I open third tab
...
t=5s - First tab stops loading, server has replied
t=10s - Second tab stops loading, server has replied
t=15s - Third tab stops loading, server has replied
t=20s - Fourth tab stops loading, server has replied
t=25s - Fifth tab stops loading, server has replied

好像后续请求开始运行直到第一个请求完成。我在这里错过了什么吗?我认为Node JS的重点是能够从单个线程运行异步设备吗?

2 个答案:

答案 0 :(得分:17)

问题不在于您的代码或Node.js - 这是您设置测试的方式。

您错误地认为您的浏览器会发出5个并发请求,但这种情况并未发生。不同的浏览器具有不同的行为,但通常浏览器将与单个源的最大同时连接数限制为非常低的数量。 HTTP规范给出了建议最大值。 我真的很惊讶地看到Chrome只打开了一个与localhost的单一连接,因为我知道Chrome打开其他来源的6个 - 只是学到了新东西!

使用其他工具来运行测试,您可以控制并确认它是否正在进行并发请求。然后你会看到预期的行为。

作为示例,我运行了您的代码并使用Apache Benchmark进行了测试,如下所示。参数表明:-n 10要发出10个请求,-c 10是使用并发10(即同时发出所有10个请求)。正如您在下面的结果中所看到的,所有请求的总时间是〜5s(以及“每个请求的时间”0.5s):

~ $ ab -n 10 -c 10 http://127.0.0.1:8080/
This is ApacheBench, Version 2.3 <$Revision: 1663405 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 127.0.0.1 (be patient).....done


Server Software:
Server Hostname:        127.0.0.1
Server Port:            8080

Document Path:          /
Document Length:        12 bytes

Concurrency Level:      10
Time taken for tests:   5.019 seconds
Complete requests:      10
Failed requests:        0
Total transferred:      1130 bytes
HTML transferred:       120 bytes
Requests per second:    1.99 [#/sec] (mean)
Time per request:       5019.151 [ms] (mean)
Time per request:       501.915 [ms] (mean, across all concurrent requests)
Transfer rate:          0.22 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.1      0       0
Processing:  5017 5018   0.3   5018    5018
Waiting:     5008 5008   0.2   5008    5009
Total:       5018 5018   0.2   5019    5019
ERROR: The median and mean for the total time are more than twice the standard
       deviation apart. These results are NOT reliable.

Percentage of the requests served within a certain time (ms)
  50%   5019
  66%   5019
  75%   5019
  80%   5019
  90%   5019
  95%   5019
  98%   5019
  99%   5019
 100%   5019 (longest request)

答案 1 :(得分:5)

似乎这只发生在某些浏览器中,我尝试使用safari,它按预期工作。 所以我猜Chrome会同时限制同一资源的相同数量