Round robin weight round-robin algorithm PHP implementation code _php skills

Source: Internet
Author: User


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.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.