-
Notifications
You must be signed in to change notification settings - Fork 64
/
weight_rr.js
42 lines (34 loc) · 1.03 KB
/
weight_rr.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
'use strict';
const utility = require('utility');
const LoadBalancer = require('./base');
const DEFAULT_WEIGHT = 100;
// 带权重的 Round Robin 算法
class WeightRoundRobinLoadBalancer extends LoadBalancer {
reset(val) {
const addressList = super.reset(val);
if (addressList) {
this._offset = utility.random(addressList.length);
}
return addressList;
}
_rr(request, addressList) {
const address = addressList[this._offset];
this._offset = (this._offset + 1) % this.size;
const weight = this.getWeight(address);
if (weight === DEFAULT_WEIGHT) return address;
if (weight === 0) return null;
const randNum = utility.random(DEFAULT_WEIGHT);
return weight >= randNum ? address : null;
}
_doSelect(request, addressList) {
let address;
let count = this.size;
while (count--) {
address = this._rr(request, addressList);
if (address) return address;
}
// 直接返回兜底
return addressList[this._offset];
}
}
module.exports = WeightRoundRobinLoadBalancer;