简体   繁体   English

带有Restify的Node.js如何处理并发请求?

[英]How Nodejs with Restify Handle Concurrent Request?

With the following code: 使用以下代码:

var counter = 0;
server.get(
    '/test,
    function(request, response, next)
    {
        console.log('Counter', ++counter);
        next();
    }
);

How does the counter variable is affected with several concurrent connections? 几个并行连接如何影响计数器变量? Restify (or Node) has some kind of connection insolation or a queue of incoming requests? Restify(或Node)是否有某种类型的连接异常或传入请求队列?

Many thanks in advance. 提前谢谢了。

Effectively, restify is wrapping one of a few different packages: spdy , http , or https . 实际上, restify封装了以下几种不同的软件包之一: spdyhttphttps

if (options.spdy) {
    this.spdy = true;
    this.server = spdy.createServer(options.spdy);
} else if ((options.cert || options.certificate) && options.key) {
    this.ca = options.ca;
    this.certificate = options.certificate || options.cert;
    this.key = options.key;
    this.passphrase = options.passphrase || null;
    this.secure = true;

    this.server = https.createServer({
        ca: self.ca,
        cert: self.certificate,
        key: self.key,
        passphrase: self.passphrase,
        rejectUnauthorized: options.rejectUnauthorized,
        requestCert: options.requestCert,
        ciphers: options.ciphers
    });
} else if (options.httpsServerOptions) {
    this.server = https.createServer(options.httpsServerOptions);
} else {
    this.server = http.createServer();
}

Source: https://github.com/restify/node-restify/blob/5.x/lib/server.js 来源: https : //github.com/restify/node-restify/blob/5.x/lib/server.js

Those packages manage the asynchronous nature of requests, which are handled as Events within restify . 这些包管理请求的异步性质,这些请求在restify作为Events处理。 The EventListener calls all listeners synchronously in the order in which they were registered. EventListener按注册顺序同步调用所有侦听器。 . In this case, restify is the listener and will process the requests in the order they are received. 在这种情况下, restify是侦听器,并将按照接收到的顺序处理请求。

Scaling 缩放比例

That being said, web servers like restify are often scaled up by releasing them on multiple processes behind a proxy like nginx . 话虽如此,像restify这样的Web服务器通常通过在诸如nginx类的代理后面的多个进程上释放它们来扩大规模。 In this case, nginx would be splitting the incoming requests between the processes effectively allowing the web server to handle a larger concurrent load. 在这种情况下, nginx将在进程之间分配传入的请求,从而有效地允许Web服务器处理更大的并发负载。

Node.js Limitations Node.js的局限性

Lastly, just keep in mind this is all limited by the behavior of Node.js. 最后,请记住,这全部受Node.js行为的限制。 Since the app runs on a single thread, you can effectively block all requests while performing a slow synchronous request. 由于该应用程序在单个线程上运行,因此您可以在执行缓慢的同步请求时有效地阻止所有请求。

server.get('/test', function(req, res, next) {
    fs.readFileSync('something.txt', ...) // blocks the other requests until done
});

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

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