Round robin weight round robin algorithm php implementation code, roundrobin

Source: Internet
Author: User

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.

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.