Code First, using PHP scripting 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();
/* Simulated 10 times */
For ($i = 0; $i < 10; $i++) {
Round_robin($hosts, $result);
}
/* Output result */
Print_r($result);
/* round robin 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 results:
Array
(
[0] => a
[1] => b
[2] => C
[3] => a
[4] => a
[5] => B
[6] => a
[7] => C
[8] => b
[9] => a
)
Load-balanced server, the implementation of its algorithm is round-robin weight round, is the back-end of the server list, to each server labeled weight, representing the probability of its adoption.
This code to the most concise process stripping out, did not consider the back-end hangs and so on, you can know how it is implemented, for reference only.