zoukankan      html  css  js  c++  java
  • 简单漏桶限流

    <?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,"	",var_dump($bucket->grant());
    }
    
    // for($i=0;$i<50;$i++){
    //     echo $i,"	",var_dump($bucket->grant());
    //     sleep(1);
    // }

  • 相关阅读:
    mapreduce 函数入门 三
    *hiho 1475
    hiho 1571
    hiho 1620
    hiho 1613
    centos下nginx配置
    hiho 1617
    hiho 172周
    uva 11584
    hiho1605
  • 原文地址:https://www.cnblogs.com/cshaptx4869/p/10462915.html
Copyright © 2011-2022 走看看