十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
本篇文章给大家介绍关于适用于 Hyperf 的计数器限流组件。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

网站建设哪家好,找创新互联!专注于网页设计、网站建设、微信开发、微信小程序、集团企业网站建设等服务项目。为回馈新老客户创新互联还提供了禹州免费建站欢迎大家使用!
说明
BETA
并对 \Psr\SimpleCache\CacheInterface 进行了补充. 增加了以下方法:
安装
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),key 默认为当前请求 fullUrl + ip. 支持字符串与闭包.2. 在exceptions配置文件中增加:
\WilburYu\HyperfCacheExt\Exception\Handler\CounterRateLimitException::class
使用
在控制器中使用计数器限速注解
#[CounterRateLimitWithRedis(maxAttempts: 5, decayMinutes: 1)]or#[CounterRateLimit(for: "common")]
如果你的缓存驱动不是 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!';
}