1. 在Laravel 中配置

在 app\Http\Kernel.php 中,默认添加到中间件组 api 下,1分钟60次。

Laravel 限流中间件 throttle 简析-LMLPHP

2. 限流原理

  1. 获取唯一请求来源,进行唯一标识(key)
  2. 获取该请求请求次数 (hits)
  3. 判断是否超过最大限制
  4. 若达到上限,进入5。未达到,则进入6
  5. 丢出访问次数限制异常,结束请求。
  6. 首先判断hits 是否达到限制,若未达到,进入7。若达到,进入8。
  7. hits 进行计数 + 1,更新到缓存中。 若是第一次,则需要 hits = 1(次数),  并添加访问标识 key (1分钟)到缓存中,以标记请求周期。
  8. 请求次数已达到上限(hits >= 60),此时需要判断是否在周期范围内(1分钟),若在周期内,进入9;不在周期内,进入10.
  9. 此时请求处在 “1分钟内请求次数达到60次”,即达到限制,返回 false 。
  10. 此时请求处在 “不在1分钟内请求次数达到60次”,即不在周期内,需要重新计算周期。

3. 代码实现

3.1 业务逻辑在 ThrottleRequests -> handle 中实现。

Laravel 限流中间件 throttle 简析-LMLPHP

    public function handle($request, Closure $next, $maxAttempts = 60, $decayMinutes = 1)
{
     // 获取唯一请求来源 2.1
$key = $this->resolveRequestSignature($request);
// 获取实际请求次数 2.2
$maxAttempts = $this->resolveMaxAttempts($request, $maxAttempts);
// 判断是否达到上限 2.3
if ($this->limiter->tooManyAttempts($key, $maxAttempts)) {
// 禁止请求 2.5
throw $this->buildException($key, $maxAttempts);
}
// 2.7 计数
$this->limiter->hit($key, $decayMinutes); $response = $next($request); return $this->addHeaders(
$response, $maxAttempts,
$this->calculateRemainingAttempts($key, $maxAttempts)
);
}

3.2 限流方法 在 Illuminate\Cache\RateLimiter 中

<?php

namespace Illuminate\Cache;

use Illuminate\Support\InteractsWithTime;
use Illuminate\Contracts\Cache\Repository as Cache; class RateLimiter
{
use InteractsWithTime; /**
* The cache store implementation.
*
* @var \Illuminate\Contracts\Cache\Repository
*/
protected $cache; /**
* Create a new rate limiter instance.
*
* @param \Illuminate\Contracts\Cache\Repository $cache
* @return void
*/ // 初始化缓存
public function __construct(Cache $cache)
{
$this->cache = $cache;
} /**
* Determine if the given key has been "accessed" too many times.
*
* @param string $key
* @param int $maxAttempts
* @return bool
*/ // 判断是否达到上限
public function tooManyAttempts($key, $maxAttempts)
{
// 判断次数,是否达到限制(60次)
if ($this->attempts($key) >= $maxAttempts) {
// 判断是否在限制周期内(1分钟内)
if ($this->cache->has($key.':timer')) {
return true;
}
// 2.10 重新计算周期
$this->resetAttempts($key);
} return false;
} /**
* Increment the counter for a given key for a given decay time.
*
* @param string $key
* @param float|int $decayMinutes
* @return int
*/
public function hit($key, $decayMinutes = 1)
{
// 对应2.7 ,添加周期缓存
$this->cache->add(
$key.':timer', $this->availableAt($decayMinutes * 60), $decayMinutes
);
// 对应2.7 ,添加请求次数缓存
$added = $this->cache->add($key, 0, $decayMinutes);
// 请求次数 + 1
$hits = (int) $this->cache->increment($key);
// 更新次数
if (! $added && $hits == 1) {
$this->cache->put($key, 1, $decayMinutes);
}
// 返回次数
return $hits;
} /**
* Get the number of attempts for the given key.
*
* @param string $key
* @return mixed
*/ // 获取请求次数,默认0
public function attempts($key)
{
return $this->cache->get($key, 0);
} /**
* Reset the number of attempts for the given key.
*
* @param string $key
* @return mixed
*/ // 重置请求周期
public function resetAttempts($key)
{
return $this->cache->forget($key);
} /**
* Get the number of retries left for the given key.
*
* @param string $key
* @param int $maxAttempts
* @return int
*/ // 获取剩余次数
public function retriesLeft($key, $maxAttempts)
{
$attempts = $this->attempts($key); return $maxAttempts - $attempts;
} /**
* Clear the hits and lockout timer for the given key.
*
* @param string $key
* @return void
*/ // 清除请求计数和周期
public function clear($key)
{
$this->resetAttempts($key); $this->cache->forget($key.':timer');
} /**
* Get the number of seconds until the "key" is accessible again.
*
* @param string $key
* @return int
*/ // 判断是否在周期内
public function availableIn($key)
{
return $this->cache->get($key.':timer') - $this->currentTime();
}
}

PS:  ThrottleRequestsWithRedis 和 ThrottleRequests 是相同的,区别在于前者指定 Redis 作为缓存,后者无限制(使用Laravel配置缓存)

05-26 07:03