新聞中心
本篇文章給大家介紹關(guān)于適用于 Hyperf 的計(jì)數(shù)器限流組件。有一定的參考價(jià)值,有需要的朋友可以參考一下,希望對(duì)大家有所幫助。

網(wǎng)站建設(shè)哪家好,找創(chuàng)新互聯(lián)!專注于網(wǎng)頁(yè)設(shè)計(jì)、網(wǎng)站建設(shè)、微信開發(fā)、微信小程序、集團(tuán)企業(yè)網(wǎng)站建設(shè)等服務(wù)項(xiàng)目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了禹州免費(fèi)建站歡迎大家使用!
說(shuō)明
BETA
并對(duì) \Psr\SimpleCache\CacheInterface 進(jìn)行了補(bǔ)充. 增加了以下方法:
- 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, // 最大允許次數(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即對(duì)應(yīng)Laravel FacadeRateLimiter::for(callable),key默認(rèn)為當(dāng)前請(qǐ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!';
} 當(dāng)前題目:可用于PHPHyperf的計(jì)數(shù)器限流組件(安裝配置)
當(dāng)前地址:http://m.fisionsoft.com.cn/article/dhjogds.html


咨詢
建站咨詢
