使用http-proxy与node.js进行负载平衡 [英] Load balancing with node.js using http-proxy

查看:105
本文介绍了使用http-proxy与node.js进行负载平衡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用node.js和http-proxy编写负载平衡代码.我想要一个负载平衡器,该负载平衡器在2个服务器之间共享传入的请求处理.

I'm trying to code a loadbalancing with node.js and http-proxy. I want a loadBalancer which share incoming request treatment between 2 servers.

var http = require('http'),
httpProxy = require('http-proxy');

 var servers =  [{host :'127.0.0.1', port :3000}, {host : 'remote_adr',port :3000}];

  httpProxy.createServer(function (req, res, proxy) {

  var target = servers.shift();
  proxy.proxyRequest(req, res, target);
  servers.push(target);


   }).listen(8000);

我认为这样做会产生一个loadBalancer,它将请求交替发送到serv1和serv2.

I thought that doing this, it would have made a loadBalancer which send requests alternately to serv1 and to serv2.

但是,当我尝试时,似乎请求的服务器没有特定顺序.另外,大多数请求都发送到我的本地主机节点服务器(127.0.0.1:3000)

However, when I try it out, it seems to request the 2 servers in no particular order. In addition most of the requests are sent to my localhost node server ( 127.0.0.1:3000 )

有人能够解释这种行为吗?

Is somebody able to explain that behavior ?

推荐答案

这应该按照您的要求进行循环,但是这是一个非常幼稚的循环.您可能会看到的是,您的favicon.ico请求在单个服务器上的请求份额比正常情况要高.例如.

That should be doing a round robin as you requested, however it's a very naive round robin. What you may be seeing is that your favicon.ico requests are putting a higher than normal share of requests on a single server. For instance.

Server 1: Actual Requests
Server 2: favicon.ico
Server 1: Another Request
Server 2: favicon.ico
Server 1: Final Request
Server 2: favicon.ico

因此,根据您的登录方式,从技术上讲,每台服务器将获得相同数量的请求时,似乎服务器1正在获得所有请求.还请记住,如果您从节点提供资产,则资产也将包含在循环机制中.因此,每个图像或文件请求也将切换到不同的节点实例.

So depending on how you're logging, it will appear that server 1 is getting all of the requests, when technically each server is getting the same number of requests. Also keep in mind that your assets will be included in the round robin as well if you're serving them from node. So each image or file request will also be handed off to a different node instance.

这篇关于使用http-proxy与node.js进行负载平衡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆