Laravel 限流中間件 throttle 簡析

 

 

1. 在Laravel 中配置php

在 app\Http\Kernel.php 中,默認添加到中間件組 api 下,1分鐘60次。api

 

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. 代碼實現app

3.1 業務邏輯在 ThrottleRequests -> handle 中實現。ui

    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 中this

<?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配置緩存)spa

相關文章
相關標籤/搜索