繁体   English   中英

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 的了解,我希望两个选项卡同时完成加载。 实际上,首先刷新的 Tab 也最先完成。 下一个选项卡在额外 10 秒后加载。 所以基本上,服务器一次处理一个请求,而不是同时处理它们。 我在这里缺少什么?

要回答你的问题并不进入细节问题的节点是如何工作的(我建议你读),你看到的行为正是我期望基于你的代码来看看。

对于每个运行的 Node 实例,都有一个处理线程,在高容量场景中,建议尽可能少地执行 CPU 密集型操作,以免阻塞该线程。 在您的示例中,每个请求都在运行 10 秒的 CPU 绑定操作,这意味着 Node 在该请求完成之前无法处理任何新请求。

如果您想更好地演示 Node 的吞吐量,请使用非阻塞示例,例如使用计时器

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

  setTimeout(() => {
    res.send({
      requestTime,
      executionTime
    });
  }, 10000);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM