php redis 令牌桶算法

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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值