0
我建立節點JSNode.js的HTTP代理集羣內的工人
var cluster = require("cluster"),
http = require("http"),
express = require('express'),
port = parseInt(process.argv[2]||8001),
servers = ['http://127.0.0.1:800821', 'http://127.0.0.1:800831'];;
if (cluster.isMaster) {
console.log('Master ' + process.pid + ' has started.');
var numWorkers = require('os').cpus().length;
console.log('Master cluster setting up ' + numWorkers + ' workers...');
for(var i = 0; i < 1; i++) {
cluster.fork();
}
cluster.on('online', function(worker) {
console.log('Worker ' + worker.process.pid + ' is online');
});
cluster.on('exit', function(worker, code, signal) {
console.log('Worker ' + worker.process.pid + ' died with code: ' + code + ', and signal: ' + signal);
console.log('Starting a new worker');
cluster.fork();
});
} else {
var httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer();
var count = 0;
// Workers share the TCP connection in this server
var app = express();
app.get('/', function (req, res) {
console.log('Cluster => ' + process.pid);
loadBalanceProxy(req,res);
}).listen(port);
var currentServer = 1;
function loadBalanceProxy(req, res){
var cur = currentServer%servers.length;
currentServer++;
var target = servers[cur];
console.log("Proxy => " + target);
proxy.web(req, res, {
target: target
});
}
}
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
res.end();
}).listen(800831);
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
res.end();
}).listen(800821);
一個示例代碼在此示例中,我想創建一個集羣內的工人代理服務器,這給了我錯誤bind EADDRINUSE null:800831
我想知道可以在集羣工作者內部創建http-proxy。如果我不能,那麼解決方案之間的負載平衡機器?
不能使用nginx的或HAProxy的? – Hosar