«

round robin权重轮循算法php实现代码

时间:2024-3-1 12:06     作者:韩俊     分类: PHP


先上代码,采用php脚本语言

<?php

/* 
 * Copyright (C) FatHong
 */

/* 数据初始化,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();

/* 模拟10次 */
for ($i = 0; $i < 10; $i++) {
  round_robin($hosts, $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;
}

输出结果:

Array
(
[0] => a
[1] => b
[2] => c
[3] => a
[4] => a
[5] => b
[6] => a
[7] => c
[8] => b
[9] => a
)

负载均衡的服务器中,其实现算法有种是round-robin权重轮循,就是后端的服务器列表中,给每个服务器标上权重,代表它被采用的机率。

这段代码把最简洁的流程剥离出来,没考虑后端挂起等情况,可以知道它是怎么实现的,仅供参考.

标签: php php教程

热门推荐