<?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); // }