Node JS是否限制为每个打开的HTTP连接一个线程?

时间:2011-03-01 00:39:44

标签: multithreading node.js

Node JS是否有多个线程在单个HTTP端口上为HTTP客户端提供服务?这是为了处理某些线程正在等待数据库或进行一些繁重处理的情况。这不应该干扰其他快速加载图像的线程。

3 个答案:

答案 0 :(得分:2)

节点不等待数据库,这就是重点。节点是非阻塞的,事件驱动的。它设置了一个回调,并继续循环,为下一个请求做好准备。它不只是坐在那里,等待数据库返回所请求的信息。

答案 1 :(得分:1)

Node.js使用event-loop,阻止的所有内容都使用threadpool => libeio (参见幻灯片63)。但话说回来你不应该担心这一点。您应该只为异步操作提供回调。操作完成后会调用它。

node_redis

为例
var redis = require("redis"),
    client1 = redis.createClient(), client2 = redis.createClient(),
    msg_count = 0;

client1.on("subscribe", function (channel, count) {
    client2.publish("a nice channel", "I am sending a message.");
    client2.publish("a nice channel", "I am sending a second message.");
    client2.publish("a nice channel", "I am sending my last message.");
});

client1.on("message", function (channel, message) {
    console.log("client1 channel " + channel + ": " + message);
    msg_count += 1;
    if (msg_count === 3) {
        client1.unsubscribe();
        client1.end();
        client2.end();
    }
});

client1.incr("did a thing");
client1.subscribe("a nice channel");

function(channel, message)例如是在事件发生时调用的其中一个回调。

function (channel, message) {
    console.log("client1 channel " + channel + ": " + message);
    msg_count += 1;
    if (msg_count === 3) {
        client1.unsubscribe();
        client1.end();
        client2.end();
    }
}

答案 2 :(得分:0)

如果您希望多个工作人员在同一端口上侦听(如果您有多个核心,则最有用),请查看the new Cluster API。来自文档的示例:

var cluster = require('cluster');
var http = require('http');
var numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
  // Fork workers.
  for (var i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', function(worker, code, signal) {
    console.log('worker ' + worker.process.pid + ' died');
  });
} else {
  // Workers can share any TCP connection
  // In this case its a HTTP server
  http.createServer(function(req, res) {
    res.writeHead(200);
    res.end("hello world\n");
  }).listen(8000);
}