大佬教程收集整理的这篇文章主要介绍了PHP实现负载均衡的加权轮询方法分析,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
本文实例讲述了PHP实现负载均衡的加权轮询方法。分享给大家供大家参考,具体如下:
通过传入不同的用户id,然后给他们分配不同的主机。
其次,需要一个存主机的数组,这些主机有不同的权重。这里的权重可以这么考虑:
假设有abc三台主机,权重分别为3,1,1,那么a的占比为0.6,b和c的占比各为0.2。
直接遍历主机的数组,假如用户来了100个人,到a的时候,a的占比是0.6,就从用户数组里随机取60个人分给a;轮到b时,b的占比是0.2,就从用户数组里随机取20人;同理,c20人,这样就完成了100个请求的转发。
可是真实场景不是固定一批用户,而是持续不断的用户请求,由于转发非常快,当来的新用户非常少时,每次从用户队列中取完、转发后立马去用户队列中取,很有可能每次只取2条,造成请求全部给了a,b和c一直没有的情况。这时候可以考虑按照不同策略从用户队列中取数据。假设以前5ms就处理完一次转发,则现在定义两种策略,如果用户队列中有100个用户时,就取出来,按着主机占比进行转发,如果用户队列中不足100人,但是当前时间和上一次取值时间相差10ms,就取出来进行转发,这样就可以累积5ms,而这5ms里队列中又会多一些用户请求,这样就不会把所有请求都分给一台机器了。
代码:
php;"> weight public $machines = array( 'a' => 3,// 0.6 'b' => 1,// 0.2 'c' => 1 // 0.2 ); // 占比 public $proportion = array(); // 用户队列 public static $user_ids = array(); public function __construct() { // 各机器的占比 $@R_789_10586@l = 0; foreach ($this->machines as $machine => $weight) { $@R_789_10586@l += $weight; } $this->proportion['a'] = $this->machines['a'] / $@R_789_10586@l; $this->proportion['b'] = $this->machines['b'] / $@R_789_10586@l; $this->proportion['c'] = $this->machines['c'] / $@R_789_10586@l; } public function getUsers() { // 用户人数 $cnt = count(self::$user_ids); $a_num = 0; $b_num = 0; $c_num = 0; if ($cnt >= self::num) { // 队列超过100人 $a_num = round(self::num * $this->proportion['a']); $b_num = round(self::num * $this->proportion['b']); $c_num = $cnt - $a_num - $b_num; } else { // 队列不足100人 $last_time = $this->last_time; // 上次访问时间 while (true) { $current_time = $this->getMillisecond(); if (($current_time - $last_timE) >= 10) { // 当前时间和上一次取值时间超过10ms $a_num = round($cnt * $this->proportion['a']); $b_num = round($cnt * $this->proportion['b']); $c_num = $cnt - $a_num - $b_num; $this->last_time = self::getMillisecond(); // 更新访问时间 break; } } } $a = array_splice(self::$user_ids,$a_num); $b = array_splice(self::$user_ids,$b_num); $c = array_splice(self::$user_ids,$c_num); return array( 'a' => $a,'b' => $b,'c' => $c ); } // 获取毫秒级时间戳 public function getMillisecond() { list($t1,$t2) = explode(" ",microtime()); return (float)sprintf('%.0f',(floatval($t1) + floatval($t2)) * 1000); } } // 测试 $wrr = new WRR(); for ($i = 0; $i < 3;="" $i++)="" {//="" 模拟持续不断的用户请求="" $random="rand(10,120);" $user_ids="range(1,$random);" wrr::$user_ids="$user_ids;" $users="$wrr-">getUsers(); print_r($users); }
以上是大佬教程为你收集整理的PHP实现负载均衡的加权轮询方法分析全部内容,希望文章能够帮你解决PHP实现负载均衡的加权轮询方法分析所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。