将请求传递到特定的分支节点实例 [英] Pass request to specific forked node instance

查看:86
本文介绍了将请求传递到特定的分支节点实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我错了,请纠正我,但是不可能在同一端口上启动多个http服务器。

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

基于此,NodeJS很有趣群集可能会分叉。因为我知道有主人将请求传递给其中一个派生的工人。哪些工作程序由操作系统或 cluster.schedulingPolicy = rr进行管理

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".

要点是:每个工作人员都需要自己的内存,所以您需要的内存是x的多倍,其中x是工作人员的数量

但是如果我想从节点应用程序中运行不同的(子)域,我也希望保留in_memory数据库的不同部分(例如,简单的JSON文件) )绑定到(子)域。或基于 subdomain.example.tdl / resource1 / whatever 之类的资源。

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.

可能。

在我看来这应该是可行的,因为我可以基于请求对象(res.url)和资源(params)进行路由不同的现有中间件。

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.

推荐答案

这是可能的:您需要在主服务器上创建网络服务器,然后通过规则将连接传递给工人http服务器:

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

这篇关于将请求传递到特定的分支节点实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆