可用于PHP Hyperf的计数器限流组件(安装配置)
说明
BETA
移植了 Laravel Cache 组件的 rate-limiter.
并对 \Psr\SimpleCache\CacheInterface
进行了补充. 增加了以下方法:
- increment
- decrement
- add
- put
安装
composer require wilbur-yu/hyperf-cache-ext
配置
1. 修改cache配置文件:
'default' => [ 'driver' => WilburYu\HyperfCacheExt\Driver\RedisDriver::class, 'packer' => WilburYu\HyperfCacheExt\Utils\Packer\PhpSerializerPacker::class, 'prefix' => env('APP_NAME', 'skeleton').':cache:', ], 'limiter' => [ 'max_attempts' => 5, // 最大允许次数 'decay_minutes' => 1, // 限流单位时间 'prefix' => 'counter-rate-limit:', // key 前缀 'for' => [ 'common' => static function (\Hyperf\HttpServer\Contract\RequestInterface $request) { return Limit::perMinute(3); }, ], 'key' => ThrottleRequest::key(), ],
for
即对应Laravel Facade
RateLimiter::for(callable)
,在服务启动时, 监听器会收集该命名限制器数组, 供在注解中使用
for
参数引用. 在注解切面执行时, 会将当前请求\Hyperf\HttpServer\Contract\RequestInterface
实例注入到该命名闭包.key
默认为当前请求fullUrl
+ip
. 支持字符串与闭包.
2. 在exceptions配置文件中增加:
\WilburYu\HyperfCacheExt\Exception\Handler\CounterRateLimitException::class
可选, 也可自行捕获, 该异常自带一个
getHeaders
方法, 值为: array(‘X-RateLimit-Limit’, ‘X-RateLimit-Remaining’, ‘Retry-After’, ‘X-RateLimit-Reset’)
使用
在控制器中使用计数器限速注解
#[CounterRateLimitWithRedis(maxAttempts: 5, decayMinutes: 1)]or#[CounterRateLimit(for: "common")]
注解参数同配置文件, 优先级为注解>配置>默认.
使用for
时,max_attempts
和decay_minutes
不起作用.
如果你的缓存驱动不是 redis
, 可以使用 CounterRateLimit
注解,反之则直接使用 CounterRateLimitWithRedis
注解即可.
在其他地方使用限速时, 可以使用辅助函数 counter_limiter()
, 使用方法同 laravel
中的 RateLimiter Facade
, 可参考 Laravel 限流文档
$executed = counter_limiter()->attempt('send-sms:'.$user->id,2,function(){ // send sms logic }); if (!$executed) { return 'Too many messages sent!'; }
推荐学习:《PHP视频教程》
-
mail.ru是什么邮箱 mail.ru邮箱登录入口 时间:2025-09-10
-
输入gpedit.msc找不到文件的原因及解决方案 时间:2025-09-10
-
nrg是什么格式文件?nrg文件用什么打开? 时间:2025-09-10
-
JavaScript中removeChild删除所有子节点方法详解(附代码) 时间:2025-09-10
-
Java运行时异常(RuntimeException)的原因及解决办法 时间:2025-09-10
-
PHP中随机数生成的方法有哪些(生成随机数的函数) 时间:2025-09-10
今日更新
-
通天排屋梗揭秘:网络热词背后的幽默文化解析
阅读:18
-
通讯兵的梗是什么梗?揭秘战场传令兵爆笑日常,看完笑到信号中断!
阅读:18
-
逆水寒手游社交能量怎么刷-社交能量获取
阅读:18
-
如鸢九月洞窟懒人版-戏学核爆与二星徐庶怎么过
阅读:18
-
最终幻想14新版本9月11日将更新-全新副本来袭
阅读:18
-
世界之外9月10日夏萧因生日更新公告完整版
阅读:18
-
闪暖×开心消消乐联动活动-9月12日更新后开启
阅读:18
-
明日之后感染者驱逐行动明日开启-珍贵奖励惊喜兑换
阅读:18
-
通讯兵梗源自军事幽默 指传递消息时总爱添油加醋的队友 网友调侃现代版传话游戏 笑点在于信息越传越离谱
阅读:18
-
原神月之一版本空月之歌呈示更新公告-完整版公告
阅读:18