首页 > 其他 > 详细

简单漏桶限流

时间:2019-03-02 21:12:52      阅读:159      评论:0      收藏:0      [点我收藏+]
<?php

/**
 * 简单的限流模型
 * 
 * 漏桶算法:
 * 水先进入到桶内,漏桶以一定的速率出水,当水流速度过大会直接溢出。
 * 主要控制数据注入网络的速率,平滑网络上的突发流量。
 */
class SmoothWarmingUp
{
    private $timestamp;
    // 桶的总容量维持不变
    public $capacity;
    // token 流出的速度
    public $rate;
    // 当前容量
    public $token;

    public function __construct()
    {
        $this->timestamp = time();
        $this->capacity = 30;
        $this->rate = 5;
    }

    public function grant()
    {
        $now = time();
        $this->token = max(0, $this->token - ($now-$this->timestamp)*$this->rate);
        $this->timestamp = $now;
        if ($this->token +1 <= $this->capacity) {
            $this->token +=1;
            return true;
        } else {
            return false;
        }
    }
}

echo ‘<pre>‘;
$bucket = new SmoothWarmingUp();
for($i=0;$i<50;$i++){
    echo $i,"\t",var_dump($bucket->grant());
}

// for($i=0;$i<50;$i++){
//     echo $i,"\t",var_dump($bucket->grant());
//     sleep(1);
// }

 

简单漏桶限流

原文:https://www.cnblogs.com/cshaptx4869/p/10462915.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!