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

Commit

Permalink
Add weightRobin for strategy.js (#1382)
Browse files Browse the repository at this point in the history
* add weightRobin strategy algorithm is refer to nginx

* change comment

---------

Co-authored-by: yufuqiang <[email protected]>
  • Loading branch information
keycodingyfq and yufuqiang authored May 9, 2024
1 parent 9a441f7 commit b762077
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions source/cluster_manager/strategy.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,42 @@ var randomlyPick = function () {
};
};

var weightRobin = function() {
let servers = [];
this.allocate = function (workers, candidates, on_ok, on_error) {
for (let i in candidates) {
let id = candidates[i];
let index = servers.findIndex(item=>{return item.name == id});
if(index==-1){
servers.push({"name": id, "cur_weight": 0});
}
index = servers.findIndex(item=>{return item.name == id});
servers[index].weight = parseInt((1 - workers[id].load) * 100);
}

for (let i = servers.length - 1; i >= 0; i--) {
if(candidates.indexOf(servers[i].name)==-1){
servers.splice(i, 1);
}
}

let index = -1;
let total = 0;
let size = servers.length;
for (let i = 0; i < size; i++) {
servers[i].cur_weight += servers[i].weight;
total += servers[i].weight;

if (index == -1 || servers[index].cur_weight < servers[i].cur_weight) {
index = i;
}
}

servers[index].cur_weight -= total;
on_ok(servers[index].name);
};
}

exports.create = function (strategy) {
switch (strategy) {
case 'least-used':
Expand All @@ -81,6 +117,8 @@ exports.create = function (strategy) {
return new roundRobin();
case 'randomly-pick':
return new randomlyPick();
case 'weight-robin':
return new weightRobin();
default:
log.warn('Invalid specified scheduling strategy:', strategy, ', apply "randomly-pick" instead.');
return new randomlyPick();
Expand Down

0 comments on commit b762077

Please sign in to comment.