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