0

Originally http.request can only connect to one host. Is there other way or other method that can specify multiple hosts for creating a http remote request client?

The reason behind that is that the remote service I'm connecting have three redundant hosts, if one go down, the others will keep working. So, i'm looking for a way to make http.request or any request client to specify multiple hosts, and connect to the one that is working. And switch to another host in the list if first one fail.

murvinlai
  • 48,919
  • 52
  • 129
  • 177

2 Answers2

1

It sounds like you want to load balance across three hosts. Is that correct? If so, then this post might help. Basically, the idea would be that you would send to the load balancer at a particular host (virtual) and then it would proxy on (round robin) to the real servers (real). For full redundancy you would need to look for a load balancer that could be clustered.

EDIT: I have used HAProxy for load balancing and have found it to work well. It lets you configure virtual hosts bound to an IP. Then from that virtual IP it forwards on to n number of real servers.

Community
  • 1
  • 1
Davin Tryon
  • 66,517
  • 15
  • 143
  • 132
0

You could just make another one until something works:

var hosts = ["first.com", "second.com", "third.com"];
(function loop(i) {
    var host = hosts[i],
        options = {
            host: host,
            port: 80,
            method: 'GET'
        };
    if (host) {
        var req = http.request(options, function(res) {
            if (res.statusCode !== 200) {
                loop(++i)
            } else {
                console.log("request succeeded");
            }
        });
        req.on("error", function() {
            loop(++i);
        });
        req.end();
    } else {
        console.log("ran out of hosts to try");
    }
})(0);
Esailija
  • 138,174
  • 23
  • 272
  • 326