如何在 Laravel 8 中动态设置速率限制器

问题描述 投票:0回答:1

我需要根据数据库表中存储的参数组合在 Laravel 8 中动态设置速率限制器:

S.否 钥匙 参数1 参数2 参数3 速率限制
1 adx param_1_a param_2_d param_3_x 20
2 嗡嗡声 param_1_b param_2_u param_3_z 30
3 cfy param_1_c param_2_f param_3_y 40

速率限制器代码如下:

protected function configureRateLimiting()
{
   RateLimiter::for('api', function (Request $request) {
      return [
        Limit::perMinute(rateLimit)->by(RateLimitKey)->response(function () {
        ...
        }),
        Limit::perMinute(rateLimit1)->by(RateLimitKey1)->response(function () {
        ...
        }),
      ];
   });
}

我需要将速率限制器添加到上面代码中返回的数组中。

RateLimit 值将是数据库表中“Rate Limit”列的值。

RateLimitKey 将是 Key、Param 1、Param 2、Param 3 列组合的值(例如 key_param1_param2_param_3)

需要使用从数据库表中检索的数据动态添加速率限制器。

我不确定如何在 Laravel 8 中添加速率限制器。

php laravel dynamic rate-limiting
1个回答
2
投票

您在上下文中有请求,因此从这里开始,只需从

DB
中获取数据。我假设它们是查询参数。请记住,这可以为空,并且需要有一个后备。

DB::table('rate_limiting_table')
    ->where('key', $request->query('key'))
    ->where('param_1', $request->query('param_1'))
    ->where('param_2', $request->query('param_2'))
    ->where('param_3', $request->query('param_3'))
    ->first();

由于这将在每个 HTTP 请求上执行,因此我建议对其进行缓存。

$cacheKey = $request->query('key') . $request->query('param_1') . $request->query('param_2') . $request->query('param_3');
cache()->remember($cacheKey, 14400, function () { // cached for 4 hours
    return ... // your query
});

将所有这些逻辑放在一起,它可能看起来像这样。进行了一些小的干净代码改进。

const DEFAULT_RATE_LIMITING = 60;

protected function configureRateLimiting()
{
    RateLimiter::for('global', function (Request $request) {
        $rateLimiting = $this->getCacheRateLimiting();

        return $rateLimiting ? $rateLimiting->rate_limit : static::DEFAULT_RATE_LIMITING;
    });
}

private function getRateLimitingDatabase(): ?object 
{
    DB::table('rate_limiting_table')
        ->where('key', $request->query('key'))
        ->where('param_1', $request->query('param_1'))
        ->where('param_2', $request->query('param_2'))
        ->where('param_3', $request->query('param_3'))
        ->first();
}

private function getCacheRateLimiting(): ?object 
{
    // cached for 4 hours
    return cache()->remember($this->getRateLimitingCacheKey(), 14400, function () {
        return  $this->getRateLimitingDatabase();
    });
}

private function getRateLimitingCacheKey(): string
{
    return $request->query('key')
        . $request->query('param_1')
        . $request->query('param_2')
        . $request->query('param_3');
}
© www.soinside.com 2019 - 2024. All rights reserved.