Nodejs Express http 服务器如何处理并发请求?

How are concurrent requests handled by Nodejs express http server?

我正在构建一个 Node.js 应用程序,想了解如何处理并发请求。

我构建了一个测试服务器,通过等待 10 秒来模拟高 CPU 负载。为了测试该行为,我打开两个浏览器选项卡并同时刷新页面。

const http      = require('http');
const express       = require('express');
const bodyParser        = require('body-parser');
const app       = express();
const server        = require('http').createServer(app);  

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.get('*', function (req, res, next) {
    var requestTime = new Date().getTime(),
            executionTime;

    doHeavyWork(requestTime, function(error){
        res.send({
            requestTime     : requestTime,
            executionTime   :   executionTime
        });
    });

});

function doHeavyWork (requestTime, callback) {
    var sleepSeconds = 10;

    while (requestTime + sleepSeconds*1000 >= new Date().getTime()) {}

    callback(null);
}

server.listen(1337, '127.0.0.1');

据我所知 Node.js,我希望两个选项卡同时完成加载。实际上,首先刷新的选项卡也首先完成。再过 10 秒后加载下一个选项卡。所以基本上,服务器一次处理一个请求,而不是同时处理它们。我在这里错过了什么?

为了回答您的问题而不深入 nitty gritty Node 的工作原理(我建议您阅读),您看到的行为正是我根据您的代码所期望看到的。

对于每个 Node 实例 运行 都有一个处理线程,在 high-volume 场景中建议尽可能少地执行 CPU-bound 操作,以免阻塞该线程。在您的示例中,每个请求都是 运行 10 秒 CPU-bound 操作,这意味着在该请求完成之前节点无法处理任何新请求。

如果您想更好地展示 Node 的吞吐量,请使用 non-blocking 示例,例如使用定时器

app.get('*', function (req, res, next) {
  var requestTime = new Date().getTime(),
        executionTime;

  setTimeout(() => {
    res.send({
      requestTime,
      executionTime: new Date().getTime()
    });
  }, 10000);
});