-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice_balancer.js
51 lines (42 loc) · 1.17 KB
/
service_balancer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
const zeromq = require("zeromq");
function ServiceBalancer(upstream) {
this.upstream = upstream;
this.dealers = [];
this.cursor_index = 0;
}
ServiceBalancer.prototype.listen = function() {
this.upstream.forEach((address) => {
this.dealers.push(createDealer(address, this.callback));
});
};
ServiceBalancer.prototype.close = function() {
this.dealers.forEach((dealer) => {
dealer.close();
});
this.dealers = [];
};
ServiceBalancer.prototype.send = function(frames) {
const handler = this.dealers[this.cursor_index];
this.cursor_index = (this.cursor_index + 1) % this.dealers.length;
handler.send(frames);
};
ServiceBalancer.prototype.onMessage = function(callback) {
this.callback = callback;
};
const createDealer = function(address, callback) {
const socket = zeromq.socket("dealer").connect(address);
socket.on("message", (...frames) => {
callback(...frames);
});
const dealer = {
address,
close: function() {
socket.close();
},
send: function(frames) {
socket.send(frames);
}
};
return dealer;
};
module.exports = ServiceBalancer;