我正在使用 http-proxy npm模块将多台服务器连接到一个端口。
我编写了以下代码并且工作正常:
var http = require('http');
var httpProxy = require('http-proxy');
// Proxy Address
var proxyAddresses = [
{
host: "localhost",
port: 3001
},
{
host: "localhost",
port: 3002
}
];
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '9090');
app.set('port', port);
//Create a set of proxy servers
var proxyServers = proxyAddresses.map(function (target) {
return new httpProxy.createProxyServer({
target: target
});
});
/**
* Create HTTP server.
*/
var server = http.createServer(function(req, res){
var proxy = proxyServers.shift();
proxy.web(req, res);
proxyServers.push(proxy);
});
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port, function(){console.log("server is listening on port " + port);});
server.on('error', onError);
server.on('listening', onListening);
我的问题:
如果我的某个服务器(例如端口3002)未启动或出现错误,我该如何自动将请求重定向到其他可用服务器(即端口3001)?
答案 0 :(得分:0)
我一直在使用http-proxy-rules扩展程序,如下所述:https://github.com/donasaur/http-proxy-rules
我设置了一些规则,如果请求的页面不存在,它会提供默认选项:
var proxyRules = new HttpProxyRules({
rules: {
'.*/test': 'http://localhost:8080/cool', // Rule (1)
'.*/test2/': 'http://localhost:8080/cool2/', // Rule (2)
'/posts/([0-9]+)/comments/([0-9]+)': 'http://localhost:8080/p/$1/c/$2', // Rule (3)
'/author/([0-9]+)/posts/([0-9]+)/': 'http://localhost:8080/a/$1/p/$2/' // Rule (4)
},
default: 'http://localhost:8080' // default target
默认位与您相关。还有一些代码表明要显示的消息:
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('The request url and path did not match any of the listed rules!');
我还没有对此进行过广泛的测试,但如果规则没有匹配,肯定会进行重定向 - 可能会对你有所帮助。