【问题标题】:Communication between several node.js process几个node.js进程之间的通信
【发布时间】:2011-09-08 10:30:17
【问题描述】:

我有 3 个 node.js 应用程序(A、B、C)。 A 是一个入口点,我喜欢将所有到达该入口点的请求重定向到 B 或 C(取决于请求中参数的值)。

目前我正在 A 中使用 res.redirect(我使用的是 expressjs 框架)。这工作正常,只是它不是真正透明的(我可以从外部看到原始请求已被重定向)。

为了解决这个问题,我会让 B 和 C 监听套接字而不是端口号,但我不知道如何让 A 将请求重定向到 B 或 C 使用的套接字。
关于如何让 2 个 node.js 进程通过套接字进行通信的任何想法?

** 更新 **

I have changed the code of A to use node-proxy:  

app.all('/port/path/*', function(req, res){

    // Host to proxied to
    var host = 'localhost';

    // Retrieve port and build new URL
    var arr_url = req.url.split('/');
    var port = arr_url[1];
    var new_url = '/' + arr_url.slice(2).join('/'); 

    console.log("CURRENT URL:" + req.url);  // url is /5000/test/...
    console.log("NEW URL    :" + new_url);  // url is /test/...

    // Change URL
    req.url = new_url;

    var proxy = new httpProxy.HttpProxy();
    proxy.proxyRequest(req, res, {
       host: host,
       port: port,
       enableXForwarded: false,
       buffer: proxy.buffer(req)
    });
    console.log("Proxied to " + host + ':' + port + new_url); 

    // For example: the url is localhost:10000/5000/test
    // the log tells me 'Proxied to localhost:5000/test' => that is correct
    // But... I do not get any return
    // If I issue 'curl -XGET http://localhost:5000/test' I get the return I expect

});

这有什么明显的错误吗?

【问题讨论】:

  • A、B、C 都是 Web 服务吗?
  • 是的,所有的网络服务都有,但我不想把 B 和 C 暴露在外面。
  • 乔希有正确的答案:将 B 和 C 绑定到 localhost,这样它们就不会暴露给外界,然后将 A 写为反向代理。 (或者使用nginx,如果A只是一个交换机。)

标签: sockets node.js


【解决方案1】:

让其他进程在不同的端口上侦听,您走在了正确的轨道上。您所说的称为反向代理。如果是 http,那么使用 node-http-proxy 就很简单了:

https://github.com/nodejitsu/node-http-proxy

您想设置代理表之类的东西:

var options = {
  router: {
    'foo.com/baz': '127.0.0.1:8001',
    'foo.com/buz': '127.0.0.1:8002',
    'bar.com/buz': '127.0.0.1:8003'
  }
};

【讨论】:

  • 我害怕端口映射不如 unix 套接字安全,你怎么看?从外面看,重定向会被看到吗?
  • 它不是 http 意义上的重定向。重定向将用户代理发送到新地址。反向代理没有,因此它对用户是透明的。大概你的机器上有防火墙,除了 80 之外都拒绝。
  • 我现在正在使用 node-proxy,你是对的,这似乎好多了,因为我无法让它工作(请参阅我的帖子的更新)。谢谢。
【解决方案2】:

我只是在这里https://github.com/nodejitsu/node-http-proxy/issues/104https://github.com/nodejitsu/node-http-proxy/issues/104提出了 node-http-rpoxy 模块的问题

显然它现在确实适用于 unix 套接字,但就像这样(可能会更改)。

var options = {
    router: {
        'foo.com/baz': ':/tmp/nodeserver.sock',
    }
};

它只需要一个冒号就可以将套接字路径用作端口值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-28
    • 2012-04-30
    • 1970-01-01
    • 1970-01-01
    • 2011-01-02
    • 2013-03-19
    • 2016-05-05
    相关资源
    最近更新 更多