您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息
免费发信息

可用于PHP Hyperf的计数器限流组件(安装配置)

2024/4/25 10:32:46发布5次查看
本篇文章给大家介绍关于适用于 hyperf 的计数器限流组件。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。
说明
beta
移植了 laravel cache 组件的 rate-limiter.
并对 \psr\simplecache\cacheinterface 进行了补充. 增加了以下方法:
incrementdecrementaddput安装
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视频教程》
以上就是可用于php hyperf的计数器限流组件(安装配置)的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录