【问题标题】:How Nodejs with Restify Handle Concurrent Request?带有 Restify 的 Nodejs 如何处理并发请求?
【发布时间】:2016-03-03 05:44:39
【问题描述】:

使用以下代码:

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

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

非常感谢。

【问题讨论】:

  • 节点(在正常情况下)仅在一个线程上运行您的应用程序,因此在单个回调中不存在并发问题。
  • @JoachimIsaksson 这应该是一个答案。
  • @HeadCode 不是节点专家我希望其他人能做出更完整的答案,这样我就不会在我不知道有一个细节的地方出错:) 没有看到它没有得到答复,所以我会在有时间的时候尝试写一些东西。

标签: node.js restify


【解决方案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
});

【讨论】:

  • 如果我错了,请纠正我:Nodejs 每个服务器实例使用一个连接队列。它是单线程的,但可扩展,因为多个实例可以在同一台或另一台机器上运行同一个应用程序,动态平衡负载(如果您使用集群模块或类似的东西)。我说的对吗?
  • Node.js 不使用每个服务器实例的连接队列。这将是每个应用程序实例。通常,nginx 之类的东西将用于缩放。不过看起来cluster 模块现在很稳定:nodejs.org/api/cluster.html。乍一看,它似乎仅限于在单个服务器上进行扩展。
猜你喜欢
  • 2018-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-25
相关资源
最近更新 更多