新聞中心
這里有您想知道的互聯網營銷解決方案
可用于PHPHyperf的計數器限流組件(安裝配置)
本篇文章給大家介紹關于適用于 Hyperf 的計數器限流組件。有一定的參考價值,有需要的朋友可以參考一下,希望對大家有所幫助。

網站建設哪家好,找創(chuàng)新互聯!專注于網頁設計、網站建設、微信開發(fā)、微信小程序、集團企業(yè)網站建設等服務項目。為回饋新老客戶創(chuàng)新互聯還提供了禹州免費建站歡迎大家使用!
說明
BETA
并對 \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 FacadeRateLimiter::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!';
} 本文題目:可用于PHPHyperf的計數器限流組件(安裝配置)
URL標題:http://www.5511xx.com/article/dhjogds.html


咨詢
建站咨詢
