简体   繁体   English

Node.js如何同时处理多个请求

[英]How does Node.js deal with multiple requests at same time

I have a Node.js app and noticed that when I madke 2 requests to my Node Api at the same time, they appear to be queued. 我有一个Node.js应用程序,注意到当我同时向我的Node Api发送2个请求时,它们似乎已排队。 Ie the time for the second request is the time for the first request plus the time for the second request (if I just fired that request on its own). 即,第二个请求的时间是第一个请求的时间加上第二个请求的时间(如果我只是自行触发该请求)。

So I did a simple test: 所以我做了一个简单的测试:

app.get('/api/testpromise', function(req, res) {

    sess = req.session;

    var controller = new Controller(req, res, sess);

    controller.testPromise()
    .then(function(){
        controller.testPromise()
        .then(function(){
             res.status(200);
             res.json({});
        });
    })
})

The testPromise() method just does a loop: testPromise()方法只是执行一个循环:

Controller.prototype.testPromise = function(callback){

    return new Promise(function(resolve, reject) {

        var count = 0;
        for (i = 0; i < 500000000; i++) {
            count++;
        }

      if(count) {
        resolve(count);
      } else {
        reject(count);
      }
    });

}

I fire off 2 requests to 'testpromise' at the same time from my frontend and the first takes approximately 5 seconds to complete and the approximately 10 seconds. 我从前端同时激发了2个“ testpromise”请求,第一个请求大约需要5秒才能完成,大约需要10秒。 So the second one appears to be queued behind the first. 因此,第二个似乎排在第一个之后。

I thought from what I had read about Node I wouldn't see behaviour like this? 我以为从阅读过的Node上我不会看到这样的行为? Node is said to be really good at taking lots of concurrent requests and handing them off. 据说Node非常擅长处理大量并发请求并将它们传递出去。 So how does this actually work? 那么,这实际上如何工作?

Your test is using blocking, synchronous code. 您的测试正在使用阻塞的同步代码。 That for-loop for (i = 0; i < 500000000; i++) will run until it is complete, so the first request in will not release control of the event loop until it is complete. for (i = 0; i < 500000000; i++) for循环将一直运行到完成为止,因此第一个请求在完成之前不会释放对事件循环的控制。 It is like a "busy wait" 就像一个“忙碌的等待”

A better test for you would be to just delay 对您来说,更好的测试是延迟

return new Promise(function(resolve, reject) {
    setTimeout( function () {
      resolve(5000) 
    }, 5000 ) // run the given function in 5000ms
});

In this way, the event loop will start the second request while the first is waiting. 这样,事件循环将在第一个请求等待时启动第二个请求。 So if you request them at the same time, both will finish at the same time. 因此,如果您同时请求它们,则两者将同时完成。

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

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