开发者

Is Node JS limited to one thread per open HTTP connection?

Can Node JS have multiple threads serving 开发者_StackOverflowHTTP clients on a single HTTP port? This is to handle situations where some threads are waiting for a database or doing some heavy processing. This is not supposed to interfere with other threads that are quick things like loading an image.


Node doesn't wait for the database, thats the point. Node is non-blocking, event-driven. It sets up a callback, and keeps going round, ready for the next request. It doesn’t just sit there, waiting for the database to come back with the requested info.


Node.js uses an event-loop and everything that is blocking uses the threadpool => libeio (See slide 63). But then again you should not worry about this. You should just provide callbacks to asynchronous operations. It gets called when operation has completed.

Take for example this snippet from 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) is for example one of these callbacks which get called when the event happens.

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


If you want to have multiple workers listening on the same port (most useful if you have multiple cores), look into the new Cluster API. Example from the docs:

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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜