nikolaposa / rate-limit
通用速率限制器实现。
3.2.0
2024-05-17 14:39 UTC
Requires
- php: ^8.1
- beberlei/assert: ^3.2
Requires (Dev)
- ext-apcu: >=5.1.12
- ext-redis: *
- friendsofphp/php-cs-fixer: 3.44
- phpstan/phpstan: ^1.10
- phpstan/phpstan-beberlei-assert: ^1.1
- phpstan/phpstan-phpunit: ^1.3
- phpunit/phpunit: ^10.5
- predis/predis: ^1.1
Suggests
- ext-apcu: In order to use ApcuRateLimiter
- ext-memcached: In order to use MemcachedRateLimiter
- ext-redis: In order to use RedisRateLimiter
- predis/predis: In order to use PredisRateLimiter
This package is auto-updated.
Last update: 2024-09-04 10:21:42 UTC
README
通用速率限制器,可用于限制某些操作可以执行的速度。默认实现使用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许可证下发布 - 详细信息请参阅许可证文件。