Skip to content

Instantly share code, notes, and snippets.

@ronkorving
Created September 29, 2011 07:45
Show Gist options
  • Select an option

  • Save ronkorving/1250211 to your computer and use it in GitHub Desktop.

Select an option

Save ronkorving/1250211 to your computer and use it in GitHub Desktop.

Revisions

  1. ronkorving created this gist Sep 29, 2011.
    35 changes: 35 additions & 0 deletions nodejs-cluster-http-proxy.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,35 @@
    var cluster = require('cluster'),
    http = require('http'),
    httpProxy = require('http-proxy');

    var httpPort = 4332;
    var clusterSock = './cluster.sock';


    var httpServer = http.createServer(function (req, res) {
    res.end('Worker! ' + process.pid);
    });

    var cl = cluster(httpServer)
    .set('workers', 5)
    .listen(clusterSock);

    if (cl.isMaster) {
    var options = {
    target: { host: 'localhost', port: clusterSock }
    };

    httpProxy.createServer(options, function (req, res, proxy) {
    if (Date.now() % 10 < 5) {
    console.log('Relaying to worker');

    proxy.proxyRequest(req, res);
    } else {
    console.log('Master response');

    res.end('Master! ' + process.pid);
    }
    }).listen(httpPort);

    console.log('HTTP proxy listening on port', httpPort);
    }