如何在 Yii2-ip-ratelimiter 中为任何动作设置不同的速率限制并重置动作的速率限制



我在项目中使用 yii2-ip-ratelimiter 来控制请求。

public function behaviors()
{
   $behaviors = parent::behaviors();
   $behaviors['rateLimiter'] = [
   // Use class
   'class' => IpRateLimiter::class,
   // The maximum number of allowed requests
   'rateLimit' => 5,
   // 5 minute - The time period for the rates to apply to
   'timePeriod' => 300,
   // Separate rate limiting for guests and authenticated users
   // Defaults to false
   // - false: use one set of rates, whether you are authenticated or not
   // - true: use separate ratesfor guests and authenticated users
  'separateRates' => false,
  // Whether to return HTTP headers containing the current rate limiting information
  'enableRateLimitHeaders' => false,
   // Array of actions on which to apply ratelimiter, if empty - applies 
   to 
   all actions
   'actions' => ['index'],
   // Allows to skip rate limiting for test environment
   'testMode' => false,
  ];
  return $behaviors;
}

我希望在某些情况下,我可以重置操作的速率限制。或者我想为任何操作设置不同的速率限制。可能吗??

请帮我怎么做?

例如,

您可以设置控制器的属性 rateLimit 属性并使用 beforeAction 进行更改

class PostController extends Controller
{
  public $rateLimit = 5;
  public function behaviors()
  {
    $behaviors = parent::behaviors();
    $behaviors['rateLimiter'] = [
      'rateLimit' => $this->rateLimit,
      // other options...
    ];
  }
  public function beforeAction($action)
  {
    // Due to lifecycle of your controllers you may change it before or after calling parent::beforeAction()
    if ($action->id === 'someAction') {
      $this->rateLimit = 3;
    }
    if (!parent::beforeAction($action)) {
        return false;
    }
    // other custom code here
    return true; // or false to not run the action
  }
}

最新更新