1.令牌桶原理
定时向桶内放一定数量令牌,每次访问拿走一个令牌,如果桶内令牌消耗完了说明超过负载.
2.php实现令牌桶
<?php class TrafficShaper { protected $redis = null; protected $max = 0; protected $queue=""; public function __construct($max,$queue) { $this->max = $max; $this->queue = $queue; $this->redis = new Redis(); $this->redis->connect("127.0.0.1",6379); } public function add($num) { $current = intval($this->redis->lLen($this->queue)); $max = intval($this->max); $num = $max-$current >$num ? $num:$max-$current; if ($num>0) { $tokens = array_fill(0,$num,1); $this->redis->lPush($this->queue,...$tokens); } return $num; } public function get() { $token = $this->redis->lPop($this->queue); return $token ? true :false; } public function reset() { $this->redis->del($this->queue); $this->add($this->max); } } $trafficShaper = new TrafficShaper(100,'limit'); $trafficShaper->reset(); $trafficShaper->add(100);