Skip to content

Commit 831a44b

Browse files
committed
[examples] updated balancer examples
1 parent ed8c9ee commit 831a44b

File tree

2 files changed

+96
-0
lines changed

2 files changed

+96
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
var http = require('http'),
2+
httpProxy = require('../../lib/http-proxy');
3+
4+
//
5+
// A simple round-robin load balancing strategy.
6+
//
7+
// First, list the servers you want to use in your rotation.
8+
//
9+
var addresses = [
10+
{
11+
host: 'ws1.0.0.0',
12+
port: 80
13+
},
14+
{
15+
host: 'ws2.0.0.0',
16+
port: 80
17+
}
18+
];
19+
20+
//
21+
// Create a HttpProxy object for each target
22+
//
23+
24+
var proxies = addresses.map(function (target) {
25+
return new httpProxy.createProxyServer({
26+
target: target
27+
});
28+
});
29+
30+
//
31+
// Get the proxy at the front of the array, put it at the end and return it
32+
// If you want a fancier balancer, put your code here
33+
//
34+
35+
function nextProxy() {
36+
var proxy = proxies.shift();
37+
proxies.push(proxy);
38+
return proxy;
39+
}
40+
41+
//
42+
// Get the 'next' proxy and send the http request
43+
//
44+
45+
var server = http.createServer(function (req, res) {
46+
nextProxy().web(req, res);
47+
});
48+
49+
//
50+
// Get the 'next' proxy and send the upgrade request
51+
//
52+
53+
server.on('upgrade', function (req, socket, head) {
54+
nextProxy().ws(req, socket, head);
55+
});
56+
57+
server.listen(8080);
58+

examples/balancer/simple-balancer.js

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
var http = require('http'),
2+
httpProxy = require('../../lib/http-proxy');
3+
//
4+
// A simple round-robin load balancing strategy.
5+
//
6+
// First, list the servers you want to use in your rotation.
7+
//
8+
var addresses = [
9+
{
10+
host: 'ws1.0.0.0',
11+
port: 80
12+
},
13+
{
14+
host: 'ws2.0.0.0',
15+
port: 80
16+
}
17+
];
18+
var proxy = httpProxy.createServer();
19+
20+
http.createServer(function (req, res) {
21+
//
22+
// On each request, get the first location from the list...
23+
//
24+
var target = { target: addresses.shift() };
25+
26+
//
27+
// ...then proxy to the server whose 'turn' it is...
28+
//
29+
console.log('balancing request to: ', target);
30+
proxy.web(req, res, target);
31+
32+
//
33+
// ...and then the server you just used becomes the last item in the list.
34+
//
35+
addresses.push(target);
36+
}).listen(8000);
37+
38+
// Rinse; repeat; enjoy.

0 commit comments

Comments
 (0)