go-limiter 实现分析

PHP + Redis 实现的滑动窗口限流器

namespace common\library\util;

class RateLimiter {

    private static function getRedis() : \Redis{
        return RedisAdapter::getConnection();
    }

    private static function UUID() : string{
        mt_srand((double)microtime() * 10000);
        return md5(uniqid(rand(), true));
    }

    static public function canAccess($id, $max=1000,$interval = 5){
        $redis = self::getRedis();
        $curTime = microtime(true);
        $startTime = $curTime - $interval;

        try {
            $members = $redis->zRangeByScore($id, $startTime, $curTime);

            $total = count($members);
            if(($total + 1) > $max){
                return false;
            }

            $uuid = self::UUID();
            $redis->zAdd($id, $curTime, $uuid);
            return true;
        } catch(\Throwable $e){
            return false;
        }
    }
}

Leave a Comment

Your email address will not be published. Required fields are marked *

PHP 8.1.1 - 16.803 ms, 0 Q