nikolaposa/rate-limit

通用速率限制器实现。

3.2.0 2024-05-17 14:39 UTC

README

Build Scrutinizer Code Quality Code Coverage Latest Stable Version PDS Skeleton

通用速率限制器,可用于限制某些操作可以执行的速度。默认实现使用Redis作为后端。

安装

首选的安装方法是使用 Composer。运行以下命令安装最新版本的包并将其添加到项目的 composer.json

composer require nikolaposa/rate-limit

使用方法

终止速率限制器

use RateLimit\Exception\LimitExceeded;
use RateLimit\Rate;
use RateLimit\RedisRateLimiter;
use Redis;

$rateLimiter = new RedisRateLimiter(Rate::perMinute(100), new Redis());

$apiKey = 'abc123';

try {
    $rateLimiter->limit($apiKey);
    
    //on success
} catch (LimitExceeded $exception) {
   //on limit exceeded
}

静默速率限制器

use RateLimit\Rate;
use RateLimit\RedisRateLimiter;
use Redis;

$rateLimiter = new RedisRateLimiter(Rate::perMinute(100), new Redis());

$ipAddress = '192.168.1.2';
$status = $rateLimiter->limitSilently($ipAddress);

echo $status->getRemainingAttempts(); //99

在项目中配置多个速率限制策略的实际用法

use RateLimit\Rate;
use RateLimit\RedisRateLimiter;

$container->set('rate_limiter.api', new RedisRateLimiter(Rate::perSecond(10), $container->get('redis')));
$container->set('rate_limiter.videos', new RedisRateLimiter(Rate::perDay(5), $container->get('redis')));

支持的驱动程序

致谢

许可协议

在MIT许可证下发布 - 详细信息请参阅许可证文件