Skip to content
This repository was archived by the owner on Oct 23, 2024. It is now read-only.

Commit b762077

Browse files
keycodingyfqyufuqiang
andauthored
Add weightRobin for strategy.js (#1382)
* add weightRobin strategy algorithm is refer to nginx * change comment --------- Co-authored-by: yufuqiang <you@example.com>
1 parent 9a441f7 commit b762077

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

source/cluster_manager/strategy.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,42 @@ var randomlyPick = function () {
6969
};
7070
};
7171

72+
var weightRobin = function() {
73+
let servers = [];
74+
this.allocate = function (workers, candidates, on_ok, on_error) {
75+
for (let i in candidates) {
76+
let id = candidates[i];
77+
let index = servers.findIndex(item=>{return item.name == id});
78+
if(index==-1){
79+
servers.push({"name": id, "cur_weight": 0});
80+
}
81+
index = servers.findIndex(item=>{return item.name == id});
82+
servers[index].weight = parseInt((1 - workers[id].load) * 100);
83+
}
84+
85+
for (let i = servers.length - 1; i >= 0; i--) {
86+
if(candidates.indexOf(servers[i].name)==-1){
87+
servers.splice(i, 1);
88+
}
89+
}
90+
91+
let index = -1;
92+
let total = 0;
93+
let size = servers.length;
94+
for (let i = 0; i < size; i++) {
95+
servers[i].cur_weight += servers[i].weight;
96+
total += servers[i].weight;
97+
98+
if (index == -1 || servers[index].cur_weight < servers[i].cur_weight) {
99+
index = i;
100+
}
101+
}
102+
103+
servers[index].cur_weight -= total;
104+
on_ok(servers[index].name);
105+
};
106+
}
107+
72108
exports.create = function (strategy) {
73109
switch (strategy) {
74110
case 'least-used':
@@ -81,6 +117,8 @@ exports.create = function (strategy) {
81117
return new roundRobin();
82118
case 'randomly-pick':
83119
return new randomlyPick();
120+
case 'weight-robin':
121+
return new weightRobin();
84122
default:
85123
log.warn('Invalid specified scheduling strategy:', strategy, ', apply "randomly-pick" instead.');
86124
return new randomlyPick();

0 commit comments

Comments
 (0)