账户范围的速率限制
Account wide Rate Limiting
官方 Yii 文档讨论了通过实施 yii\filters\RateLimitInterface on a user identity class.
为 api 添加速率限制
https://www.yiiframework.com/doc/guide/2.0/en/rest-rate-limiting
但是是否可以对 class 不是用户 class 的用户实施速率限制?
例如,在我的 api 中,一个用户属于一个帐户。
一个帐户有很多用户。
是否可以对每个帐户而不是每个用户实施速率限制?如果有怎么办?
您有两种选择。
第一个选项是在相同的 class 中实施 RateLimitInterface
,在您的帐户模型中实施 IdentityInterface
但 load/store 津贴。
如果您的 User
模型实现了 IdentityInterface
并且具有 Account
关系,它可能如下所示:
class User extends ActiveRecord implements IdentityInterface, RateLimitInterface
{
public function getRateLimit($request, $action)
{
return [$this->account->rateLimit, 1]; // $rateLimit requests per second
}
public function loadAllowance($request, $action)
{
return [$this->account->allowance, $this->account->allowance_updated_at];
}
public function saveAllowance($request, $action, $allowance, $timestamp)
{
$this->account->allowance = $allowance;
$this->account->allowance_updated_at = $timestamp;
$this->account->save();
}
// ... the rest of User class definitions ...
}
第二个选择是让其他一些 class 实现 RateLimitInterface
并在 yii\filters\RateLimiter::$user
到 return 实例 class 中使用闭包。
官方 Yii 文档讨论了通过实施 yii\filters\RateLimitInterface on a user identity class.
为 api 添加速率限制https://www.yiiframework.com/doc/guide/2.0/en/rest-rate-limiting
但是是否可以对 class 不是用户 class 的用户实施速率限制?
例如,在我的 api 中,一个用户属于一个帐户。 一个帐户有很多用户。
是否可以对每个帐户而不是每个用户实施速率限制?如果有怎么办?
您有两种选择。
第一个选项是在相同的 class 中实施 RateLimitInterface
,在您的帐户模型中实施 IdentityInterface
但 load/store 津贴。
如果您的 User
模型实现了 IdentityInterface
并且具有 Account
关系,它可能如下所示:
class User extends ActiveRecord implements IdentityInterface, RateLimitInterface
{
public function getRateLimit($request, $action)
{
return [$this->account->rateLimit, 1]; // $rateLimit requests per second
}
public function loadAllowance($request, $action)
{
return [$this->account->allowance, $this->account->allowance_updated_at];
}
public function saveAllowance($request, $action, $allowance, $timestamp)
{
$this->account->allowance = $allowance;
$this->account->allowance_updated_at = $timestamp;
$this->account->save();
}
// ... the rest of User class definitions ...
}
第二个选择是让其他一些 class 实现 RateLimitInterface
并在 yii\filters\RateLimiter::$user
到 return 实例 class 中使用闭包。