本篇文章給大家介紹關(guān)于適用于 Hyperf 的計(jì)數(shù)器限流組件。有一定的參考價(jià)值,有需要的朋友可以參考一下,希望對(duì)大家有所幫助。
說(shuō)明
BETA
移植了 Laravel Cache 組件的 rate-limiter.
并對(duì) PsrSimpleCacheCacheInterface
進(jìn)行了補(bǔ)充. 增加了以下方法:
- increment
- decrement
- add
- put
安裝
composer require wilbur-yu/hyperf-cache-ext
配置
1. 修改cache配置文件:
'default' => [ 'driver' => WilburYuHyperfCacheExtDriverRedisDriver::class, 'packer' => WilburYuHyperfCacheExtUtilsPackerPhpSerializerPacker::class, 'prefix' => env('APP_NAME', 'skeleton').':cache:', ], 'limiter' => [ 'max_attempts' => 5, // 最大允許次數(shù) 'decay_minutes' => 1, // 限流單位時(shí)間 'prefix' => 'counter-rate-limit:', // key 前綴 'for' => [ 'common' => static function (HyperfHttpServerContractRequestInterface $request) { return Limit::perMinute(3); }, ], 'key' => ThrottleRequest::key(), ],
for
即對(duì)應(yīng)Laravel Facade
RateLimiter::for(callable)
,
在服務(wù)啟動(dòng)時(shí), 監(jiān)聽(tīng)器會(huì)收集該命名限制器數(shù)組, 供在注解中使用
for
參數(shù)引用. 在注解切面執(zhí)行時(shí), 會(huì)將當(dāng)前請(qǐng)求HyperfHttpServerContractRequestInterface
實(shí)例注入到該命名閉包.key
默認(rèn)為當(dāng)前請(qǐng)求fullUrl
+ip
. 支持字符串與閉包.
2. 在exceptions配置文件中增加:
WilburYuHyperfCacheExtExceptionHandlerCounterRateLimitException::class
可選, 也可自行捕獲, 該異常自帶一個(gè)
getHeaders
方法, 值為: array(‘X-RateLimit-Limit’, ‘X-RateLimit-Remaining’, ‘Retry-After’, ‘X-RateLimit-Reset’)
使用
在控制器中使用計(jì)數(shù)器限速注解
#[CounterRateLimitWithRedis(maxAttempts: 5, decayMinutes: 1)]or#[CounterRateLimit(for: "common")]
注解參數(shù)同配置文件, 優(yōu)先級(jí)為注解>配置>默認(rèn).
使用for
時(shí),max_attempts
和decay_minutes
不起作用.
如果你的緩存驅(qū)動(dòng)不是 redis
, 可以使用 CounterRateLimit
注解,反之則直接使用 CounterRateLimitWithRedis
注解即可.
在其他地方使用限速時(shí), 可以使用輔助函數(shù) 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!'; }
推薦學(xué)習(xí):《PHP視頻教程》