redisトークンバケツアルゴリズムの実現構想

17213 ワード

1.よく使われるストリーム制限構想トークンバケツアルゴリズムとバケツ漏れアルゴリズム
ダイレクトトークンバケツアルゴリズムコード


class TokenBucket{
     
    private  $_config; //redis  
    private $_redis;  //redis  
    private $_queue;  //   
    private $_max;  //     

    /**
     *   redis  
     * @return Redis
     */
    private function connect()
    {
     
        $redis = new Redis();
        $redis->connect('127.0.0.1',6379);
        $redis->select($this->_config['index']);//           ,       index       ,  0        。
        return $redis;
    }


    public function __construct($config ,$queue,$max)
    {
     
        $this->_config = $config;
        $this->_queue = $queue;
        $this->_max = $max;
        $this->_redis = $this->connect();
    }

    /**
     *    
     */
    public function get()
    {
     
        return $this->_redis->rPop($this->_queue)?true:false;
    }

    /**
     *     
     * @param int $num
     * @return int
     */
    public function add($num =0)
    {
     
        $currNum = $this->_redis->lSize($this->_queue);

        $maxNum = $this->_max;

        $num = $maxNum >$currNum+$num?$num:$maxNum-$currNum;
        if ($num >0){
     
            $token = array_fill(0,$num,1);
            $this->_redis->lPush($this->_queue,...$token);
            return $num;
        }
        return 0;
    }

    /**
     *         ,    
     */
    public function reset()
    {
     
        $this->_redis->delete($this->_queue);
        $this->add($this->_max);
    }
}

// redis    
$config = array(
    'host' => 'localhost',
    'port' => 6379,
    'index' => 0,
    'auth' => '',
    'timeout' => 1,
    'reserved' => NULL,
    'retry_interval' => 100,
);

$queue = "mycontainer";

$max = 5;

$tokenBucket = new TokenBucket($config,$queue,$max);
$tokenBucket->reset();

//       ,      5   ,    3     
for($i=0; $i<8; $i++){
     
    var_dump($tokenBucket->get());
}

//   10   ,     5,      5 
$add_num = $tokenBucket->add(10);

var_dump($add_num);

//       ,      5   ,    1     
for($i=0; $i<6; $i++){
     
    var_dump($tokenBucket->get());
}