加入收藏 | 设为首页 | 会员中心 | 我要投稿 阜阳站长网 (https://www.0558zz.cn/)- AI行业应用、低代码、混合云存储、数据仓库、物联网!
当前位置: 首页 > 运营中心 > 建站资源 > 优化 > 正文

可用于PHP Hyperf的计数器限流组件

发布时间:2022-08-11 11:33:09 所属栏目:优化 来源:互联网
导读:本篇文章给大家介绍关于适用于 Hyperf 的计数器限流组件。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。 说明 BETA 移植了 Laravel Cache 组件的 rate-limiter. 并对 PsrSimpleCacheCacheInterface 进行了补充. 增加了以下方法: inc
  本篇文章给大家介绍关于适用于 Hyperf 的计数器限流组件。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。
  说明
 
  BETA
 
  移植了 Laravel Cache 组件的 rate-limiter.
 
  并对 PsrSimpleCacheCacheInterface 进行了补充. 增加了以下方法:
 
  increment
  decrement
  add
  put
  安装
 
 
  composer require wilbur-yu/hyperf-cache-ext
 
  配置
 
  1. 修改cache配置文件:
 
 
 
 
  'default' => [
 
      'driver' => WilburYuHyperfCacheExtDriverRedisDriver::class,
 
      'packer' => WilburYuHyperfCacheExtUtilsPackerPhpSerializerPacker::class,
 
      'prefix' => env('APP_NAME', 'skeleton').':cache:',
 
  ],
 
  'limiter' => [
 
      'max_attempts' => 5,  // 最大允许次数
 
      'decay_minutes' => 1, // 限流单位时间
 
      'prefix' => 'counter-rate-limit:', // key 前缀
 
      'for' => [
 
          'common' => static function (HyperfHttpServerContractRequestInterface $request) {
 
              return Limit::perMinute(3);
 
          },
 
      ],
 
      'key' => ThrottleRequest::key(),
 
  ],
 
  for 即对应 Laravel Facade RateLimiter::for(callable),
  在服务启动时, 监听器会收集该命名限制器数组, 供在注解中使用 for 参数引用. 在注解切面执行时, 会将当前请求 HyperfHttpServerContractRequestInterface 实例注入到该命名闭包.
 
  key 默认为当前请求 fullUrl + ip. 支持字符串与闭包.
  2. 在exceptions配置文件中增加:
 
 
  WilburYuHyperfCacheExtExceptionHandlerCounterRateLimitException::class
 
  可选, 也可自行捕获, 该异常自带一个 getHeaders 方法, 值为: array(‘X-RateLimit-Limit’, ‘X-RateLimit-Remaining’, ‘Retry-After’, ‘X-RateLimit-Reset’)
 
  使用
 
  在控制器中使用计数器限速注解
 
 
  #[CounterRateLimitWithRedis(maxAttempts: 5, decayMinutes: 1)]or#[CounterRateLimit(for: "common")]
 
  注解参数同配置文件, 优先级为注解>配置>默认.
  使用 for 时, max_attempts 和 decay_minutes 不起作用.
 
  如果你的缓存驱动不是 redis, 可以使用 CounterRateLimit 注解,反之则直接使用 CounterRateLimitWithRedis 注解即可.
 
  在其他地方使用限速时, 可以使用辅助函数 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!';
 
  }

(编辑:阜阳站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读