@@ -69,6 +69,42 @@ var randomlyPick = function () {
69
69
} ;
70
70
} ;
71
71
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
+
72
108
exports . create = function ( strategy ) {
73
109
switch ( strategy ) {
74
110
case 'least-used' :
@@ -81,6 +117,8 @@ exports.create = function (strategy) {
81
117
return new roundRobin ( ) ;
82
118
case 'randomly-pick' :
83
119
return new randomlyPick ( ) ;
120
+ case 'weight-robin' :
121
+ return new weightRobin ( ) ;
84
122
default :
85
123
log . warn ( 'Invalid specified scheduling strategy:' , strategy , ', apply "randomly-pick" instead.' ) ;
86
124
return new randomlyPick ( ) ;
0 commit comments