简体   繁体   English

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

[英]How are concurrent requests handled by Nodejs express http server?

I am building a Node.js application and wanted to understand how concurrent requests are handled.我正在构建一个 Node.js 应用程序并想了解如何处理并发请求。

I build a test server, where high CPU load is being simulated by waiting 10 seconds.我构建了一个测试服务器,通过等待 10 秒来模拟高 CPU 负载。 To test the behavior, I open two browser tabs and refresh the page simultaneously.为了测试行为,我打开两个浏览器选项卡并同时刷新页面。

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

From what I heard about Node.js, I was expecting both Tabs to finish loading in the same time.根据我对 Node.js 的了解,我希望两个选项卡同时完成加载。 In reality the Tab which is refreshed first also finishes first.实际上,首先刷新的 Tab 也最先完成。 The next tab loads after additional 10 seconds.下一个选项卡在额外 10 秒后加载。 So basically, the server processes the requests one at a time instead of processing them simultaneously.所以基本上,服务器一次处理一个请求,而不是同时处理它们。 What am I missing here?我在这里缺少什么?

To answer your question without getting into the nitty gritty of how Node works (which I advise you read), the behaviour you see is exactly what I'd expect to see based on your code.要回答你的问题并不进入细节问题的节点是如何工作的(我建议你读),你看到的行为正是我期望基于你的代码来看看。

For each Node instance running there is a single processing thread, in high-volume scenarios it's recommended to do as little CPU-bound operations as possible as to not block that thread.对于每个运行的 Node 实例,都有一个处理线程,在高容量场景中,建议尽可能少地执行 CPU 密集型操作,以免阻塞该线程。 In your example, each request is running a 10s CPU-bound operation which means Node can't process any new requests until that request completes.在您的示例中,每个请求都在运行 10 秒的 CPU 绑定操作,这意味着 Node 在该请求完成之前无法处理任何新请求。

If you want to better demonstrate the throughput of Node, use a non-blocking example eg use of a timer如果您想更好地演示 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