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

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

藏色散人
Release: 2023-04-10 21:10:02
forward
5358 people have browsed it

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
Copy after login

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(),
],
Copy after login
  • 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
Copy after login

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")]
Copy after login

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!';
}
Copy after login

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!

Related labels:
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template