Nodejs如何处理并发请求?

时间:2016-02-29 08:07:49

标签: node.js restify

使用以下代码:

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

计数器变量如何受到多个并发连接的影响? Restify(或Node)有某种连接日照或传入请求队列吗?

非常感谢提前。

1 个答案:

答案 0 :(得分:1)

实际上,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();
}

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

这些包管理请求的异步性质,这些请求在restify内作为事件处理。 The EventListener calls all listeners synchronously in the order in which they were registered.。在这种情况下,restify是监听器,将按接收顺序处理请求。

<强>缩放

话虽如此,像restify这样的网络服务器通常会通过像nginx这样的代理后面的多个进程发布它们来扩展。在这种情况下,nginx将在进程之间拆分传入请求,从而有效地允许Web服务器处理更大的并发负载。

Node.js限制

最后,请记住,这一切都受到Node.js行为的限制。由于应用程序在单个线程上运行,因此您可以在执行慢速同步请求时有效地阻止所有请求。

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