掃二維碼與項(xiàng)目經(jīng)理溝通
我們在微信上24小時(shí)期待你的聲音
解答本文疑問/技術(shù)咨詢/運(yùn)營咨詢/技術(shù)建議/互聯(lián)網(wǎng)交流
本篇文章給大家介紹關(guān)于適用于 Hyperf 的計(jì)數(shù)器限流組件。有一定的參考價(jià)值,有需要的朋友可以參考一下,希望對大家有所幫助。

網(wǎng)站建設(shè)哪家好,找創(chuàng)新互聯(lián)!專注于網(wǎng)頁設(shè)計(jì)、網(wǎng)站建設(shè)、微信開發(fā)、微信小程序、集團(tuán)企業(yè)網(wǎng)站建設(shè)等服務(wù)項(xiàng)目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了禹州免費(fèi)建站歡迎大家使用!
說明
BETA
并對 \Psr\SimpleCache\CacheInterface 進(jìn)行了補(bǔ)充. 增加了以下方法:
安裝
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, // 最大允許次數(shù)
'decay_minutes' => 1, // 限流單位時(shí)間
'prefix' => 'counter-rate-limit:', // key 前綴
'for' => [
'common' => static function (\Hyperf\HttpServer\Contract\RequestInterface $request) {
return Limit::perMinute(3);
},
],
'key' => ThrottleRequest::key(),
],
for 即對應(yīng) Laravel Facade RateLimiter::for(callable),key 默認(rèn)為當(dāng)前請求 fullUrl + ip. 支持字符串與閉包.2. 在exceptions配置文件中增加:
\WilburYu\HyperfCacheExt\Exception\Handler\CounterRateLimitException::class
使用
在控制器中使用計(jì)數(shù)器限速注解
#[CounterRateLimitWithRedis(maxAttempts: 5, decayMinutes: 1)]or#[CounterRateLimit(for: "common")]
如果你的緩存驅(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!';
} 
我們在微信上24小時(shí)期待你的聲音
解答本文疑問/技術(shù)咨詢/運(yùn)營咨詢/技術(shù)建議/互聯(lián)網(wǎng)交流