Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass request to specific forked node instance

Correct me if I am wrong, but it isn't possible to start multiple http-servers on the same port.

Based on this it is interesting the NodeJS cluster may fork. Of cause I know there is the master what is passing the request to one of the forked workers. What worker is managed by operating system or cluster.schedulingPolicy= "rr" for "round robin".

The point is: Every worker needs its own memory, so you need x-times much memory where x is the number of workers.

But if I like to run different (sub)domains out of my node app, I also like to hold different parts of an in_memory database (e.g. a simple JSON file) bound to a (sub)domain. OR based on resources like subdomain.example.tdl/resource1/whatever.

It doesn't seams to be possible. Either resource based nor domain based.

In my opinion it should be possible, because I can route based on request-objects (res.url) and resources (params) by different existing middleware.

So that way it should be possible to tell the master to pass the request to a specific forked instance.

like image 667
Danny Avatar asked Jul 10 '15 11:07

Danny


1 Answers

It's possible: you need create net server at master, and pass connection by you rules to workers http server:

var cluster = require('cluster');

if (cluster.isMaster) {
    var workers = [];    

    // Create workers
    for (var i=0; i<require('os').cpus().length; i++) {
        workers[i] = cluster.fork({WORKER_INDEX:i, JSON_INDEX:i});
    }

    // Create net server at master
    var server = require('net').createServer({pauseOnConnect:true}, function(c) {
        var b = Math.floor( Math.random()*workers.length );
        workers[b].send("doit",c);
    }).listen(3000);
} else {

    // Load specific data for worker (pass parametr JSON_INDEX)
    var json = "{default:default}";   
    try {
        json = require("fs").readFileSync('./data_'+process.env.JSON_INDEX+'.json');
    } catch (e) {}

    // Create http server and pass specific json to client
    var server = require('http').createServer( function(req, res) {
      res.writeHead(200, {'Content-Type': 'text/plain'});
      res.end(json);
    }).listen(0,'127.0.0.1');

    // Get message from master and check if need pass to http server
    process.on('message', function(m,c) {
        if ( "doit" === m ) {
            server.emit('connection', c);
            c.resume();
        }
    });
}
like image 172
stdob-- Avatar answered Oct 18 '22 06:10

stdob--