Home  >  Article  >  Backend Development  >  Counter current limiting component available for PHP Hyperf (installation configuration)

Counter current limiting component available for PHP Hyperf (installation configuration)

藏色散人
藏色散人forward
2022-01-11 15:31:555302browse

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:

  • increment
  • decrement
  • add
  • put

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 using for, max_attempts and decay_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!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete