Round robin weight round robin algorithm php implementation code, roundrobin
First, use the php script language.
<? Php/** Copyright (C) FatHong * // * Data initialization, weight: weight */$ hosts ['a'] = array ('weight' => 5, 'Current _ weight' => 0, 'Count' => 0); $ hosts ['B'] = array ('weight' => 3, 'Current _ weight' => 0, 'Count' => 0); $ hosts ['C'] = array ('weight' => 2, 'Current _ weight '=> 0, 'Count' => 0); $ result = array ();/* simulate 10 times */for ($ I = 0; $ I <10; $ I ++) {round_robin ($ hosts, $ result);}/* output result */print_r ($ result ); /* round robin */function round_robin (& $ hosts, & $ result) {$ total = 0; $ best = null; foreach ($ hosts as $ key => $ item) {$ current = & $ hosts [$ key]; $ weight = $ current ['weight']; $ current ['current _ weight '] + = $ weight; $ total + = $ weight; if ($ best = null) | ($ hosts [$ best] ['current _ weight '] <$ current ['current _ weight']) {$ best = $ key ;}} $ hosts [$ best] ['current _ weight ']-= $ total; $ hosts [$ best] ['Count'] ++; $ result [] = $ best ;}
Output result:
Array
(
[0] =>
[1] => B
[2] => c
[3] =>
[4] =>
[5] => B
[6] =>
[7] => c
[8] => B
[9] =>
)
In the Server Load balancer server, the implementation algorithm is round-robin Weighted round robin, that is, in the back-end server list, each server is assigned a weight, representing its probability of being used.
This Code separates the most concise process and does not consider backend suspension. You can see how it is implemented for your reference only.