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

时间:2019-03-27 08:18:06

标签: yii2

我在项目中使用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;
}

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

请帮我怎么做?

1 个答案:

答案 0 :(得分:0)

例如,您可以设置控制器的属性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
  }
}