繁体   English   中英

Nodejs:http-proxy重定向到可用服务器

[英]Nodejs: http-proxy redirect to available server

我使用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)?

我一直在使用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!');

我没有对此进行过广泛的测试,但如果规则不匹配,肯定会进行重定向 - 可能对您有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM