如何在 laravel Rate Limit 中对不同数量的请求应用不同的延迟?

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

我正在制作一个速率限制中间件,我必须在其中执行以下功能 1:第一个请求是即时发送,第二个请求将要求您等待 30 秒,第三个请求将要求您等待 60 秒,第四个请求将要求您等待 120 秒(这是按数字排列的) 2:如果该ip在一分钟内发送10个请求,则阻塞3小时。 但我被困在这里,没有得到尝试次数,我无法添加自定义延迟功能,你能告诉我哪里出错了以及该怎么办吗?我是第一次应用这些

public function handle($request, Closure $next)
    {
        $limiter = app(RateLimiter::class);
        $key = sha1($request->ip());
        $maxAttempts = 4;
        $hitCount = $limiter->attempts($key);
        if ($hitCount == 2)
        {
            $decayMinutes = 30;
        }
        elseif ($hitCount == 3)
        {
            $decayMinutes = 60;
        }
        elseif ($hitCount == 4)
        {
            $decayMinutes = 120;
        }
        else
        {
            $decayMinutes = 10;
        }
        if ($limiter->tooManyAttempts($key, $maxAttempts))
        {
            $retryAfter = $limiter->availableIn($key);
            return new Response('Rate limit exceeded. Please wait ' . $retryAfter . ' seconds before making another request.', 429);
        }

        $limiter->hit($key, $decayMinutes);
        $response = $next($request);
        return $response;
    }

现在这段代码正在连续发送请求,无需任何等待。

我已经尝试过此操作,没有任何计数命中,最大尝试次数 1 它工作正常,但现在我尝试为不同数量的请求提供不同的延迟,但它没有按预期工作。

php laravel middleware rate-limiting laravel-middleware
1个回答
0
投票

请尝试一下......

public function handle($request, Closure $next)
 {
    $limiter = app(RateLimiter::class);
    $key = sha1($request->ip());
    $maxAttempts = 4;
    $decayMinutes = 10; // Default decay time

    if ($limiter->tooManyAttempts($key, $maxAttempts)) {
      $retryAfter = $limiter->availableIn($key);
      return new Response('Rate limit exceeded. Please wait ' . $retryAfter . ' 
      seconds before making another request.', 429);
    }

    $hitCount = $limiter->attempts($key);
    if ($hitCount == 2) {
         $decayMinutes = 30;
      } elseif ($hitCount == 3) {
         $decayMinutes = 60;
      } elseif ($hitCount == 4) {
        $decayMinutes = 120;
    }

  $limiter->hit($key, $decayMinutes);
  $response = $next($request);
  return $response;
}
© www.soinside.com 2019 - 2024. All rights reserved.