This article introduces you to the counter current limiting component suitable for Hyperf. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
Description
BETA
Ported the rate-limiter of Laravel Cache component.
and corrected \Psr\SimpleCache\CacheInterface
has been supplemented. The following methods have been added:
Installation
composer require wilbur-yu/hyperf-cache-ext
Configuration
1. Modify the cache configuration file:
'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
, which corresponds to Laravel Facade
RateLimiter::for(callable)
,When the service starts, the listener will collect the named limiter array for use in the annotation
for
parameter reference. When the annotation aspect is executed, the current request\Hyperf\ HttpServer\Contract\RequestInterface
instance is injected into this named closure.
key
Defaults to the current requestfullUrl
ip
. Supports strings and closures.2. Add:
\WilburYu\HyperfCacheExt\Exception\Handler\CounterRateLimitException::class
in the exceptions configuration file. Optional, you can also catch it yourself. The exception will be automatically With a
getHeaders
method, the value is: array('X-RateLimit-Limit', 'X-RateLimit-Remaining', 'Retry-After', 'X-RateLimit-Reset')
Use
Use counter speed limit in the controller annotation
#[CounterRateLimitWithRedis(maxAttempts: 5, decayMinutes: 1)]or#[CounterRateLimit(for: "common")]
The annotation parameters are the same as those in the configuration file, take precedence Level is Annotation>Configuration>Default.
When usingfor
,max_attempts
anddecay_minutes
have no effect.
If your cache driver is not redis
, you can use the CounterRateLimit
annotation, otherwise you can directly use the CounterRateLimitWithRedis
annotation.
elsewhere When using rate limiting, you can use the auxiliary function counter_limiter()
. The usage method is the same as RateLimiter Facade
in laravel
. Please refer to Laravel current limiting document
$executed = counter_limiter()->attempt('send-sms:'.$user->id,2,function(){ // send sms logic }); if (!$executed) { return 'Too many messages sent!'; }
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of Counter current limiting component available for PHP Hyperf (installation configuration). For more information, please follow other related articles on the PHP Chinese website!