Throttle中间件怎么用?Laravel请求频率限制示例

PHP 投稿 57000 0 评论

Throttle中间件怎么用?Laravel请求频率限制示例

Throttle频次数据存储在cache里的,Laravel默认的cache driver是file也就是throttle信息会默认存储在cache文件里, 如果你的cache driver换成redis那么这些信息就会存储在redis里,记录的信息其实很简单,Throttle会将请求对象的signature(以HTTP请求方法、域名、URI和客户端IP做哈希)作为缓存key记录客户端的请求次数。

什么是访问频次限制

频次限制经常用在API中,用于限制独立请求者对特定API的请求频率。当设置频次限制为每分钟1000次,如果一分钟内超过这个限制,那么服务器就会返回 429: Too Many Attempts.响应。

通常,一个编码良好的、实现了频率限制的应用还会回传三个响应头: 

X-RateLimit-Limit,,X-RateLimit-Remaining,Retry-After(Retry-After头只有在达到限制次数后才会返回)

X-RateLimit-Limit告诉我们在指定时间内允许的最大请求次数

X-RateLimit-Remaining指的是在指定时间段内剩下的请求次数

Retry-After指的是距离下次重试请求需要等待的时间(s)

注意:每个应用都会选择一个自己的频率限制时间跨度,Laravel应用访问频率限制的时间跨度是一分钟,所以频率限制限制的是一分钟内的访问次数。

使用Throttle中间件

中间件的使用方法首先要定义一个路由,将中间件throttle添加到其中,throttle默认限制每分钟尝试60次,并且在一分钟内访问次数达到60次后禁止访问:

Route::group(['prefix'=>'api','middleware'=>'throttle'], function(){
    Route::get('users', function(){
        return \App\User::all();
    });
});

访问路由/api/users时你会看见响应头里有如下的信息:

X-RateLimit-Limit: 60

X-RateLimit-Remaining: 58

如果请求超频,响应头里会返回Retry-After:

Retry-After: 58

X-RateLimit-Limit: 60

X-RateLimit-Remaining: 0

上面的信息表示58秒后页面或者API的访问才能恢复正常。

定义频率和重试等待时间

频率默认是60次可以通过throttle中间件的第一个参数来指定你想要的频率,重试等待时间默认是一分钟可以通过throttle中间件的第二个参数来指定你想要的分钟数。

//频次上限5
Route::group(['prefix'=>'api','middleware'=>'throttle:5'],function(){
    Route::get('users',function(){
        return \App\User::all();
    });
});
//频次上限5,重试等待时间10分钟
Route::group(['prefix'=>'api','middleware'=>'throttle:5,10'],function(){
    Route::get('users',function(){
        return \App\User::all();
    });
});

自定义Throttle中间件,返回API响应

在请求频次达到上限后Throttle除了返回那些响应头,返回的响应内容是一个HTML页面,页面上告诉我们Too Many Attempts。在调用API的时候我们显然更希望得到一个json响应,下面提供一个自定义的中间件替代默认的Throttle中间件来自定义响应信息。

首先创建一个ThrottleRequests中间件: 

php artisan make:middleware ThrottleRequests.

将下面的代码拷贝到app/Http/Middlewares/ThrottleReuqests文件中:

namespace App\Http\Middleware;
use Closure;
use Illuminate\Cache\RateLimiter;
use Symfony\Component\HttpFoundation\Response;
class ThrottleRequests
{
    /**
     * The rate limiter instance.
     *
     * @var \Illuminate\Cache\RateLimiter
     */
    protected $limiter;
    /**
     * Create a new request throttler.
     *
     * @param  \Illuminate\Cache\RateLimiter $limiter
     */
    public function __construct(RateLimiter $limiter)
    {
        $this->limiter = $limiter;
    }
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @param  int $maxAttempts
     * @param  int $decayMinutes
     * @return mixed
     */
    public function handle($request, Closure $next, $maxAttempts = 60, $decayMinutes = 1)
    {
        $key = $this->resolveRequestSignature($request);
        if ($this->limiter->tooManyAttempts($key, $maxAttempts, $decayMinutes)) {
            return $this->buildResponse($key, $maxAttempts);
        }
        $this->limiter->hit($key, $decayMinutes);
        $response = $next($request);
        return $this->addHeaders(
            $response, $maxAttempts,
            $this->calculateRemainingAttempts($key, $maxAttempts)
        );
    }
    /**
     * Resolve request signature.
     *
     * @param  \Illuminate\Http\Request $request
     * @return string
     */
    protected function resolveRequestSignature($request)
    {
        return $request->fingerprint();
    }
    /**
     * Create a 'too many attempts' response.
     *
     * @param  string $key
     * @param  int $maxAttempts
     * @return \Illuminate\Http\Response
     */
    protected function buildResponse($key, $maxAttempts)
    {
        $message = json_encode([
            'error' => [
                'message' => 'Too many attempts, please slow down the request.' //may comes from lang file
            ],
            'status_code' => 4029 //your custom code
        ]);
        $response = new Response($message, 429);
        $retryAfter = $this->limiter->availableIn($key);
        return $this->addHeaders(
            $response, $maxAttempts,
            $this->calculateRemainingAttempts($key, $maxAttempts, $retryAfter),
            $retryAfter
        );
    }
    /**
     * Add the limit header information to the given response.
     *
     * @param  \Symfony\Component\HttpFoundation\Response $response
     * @param  int $maxAttempts
     * @param  int $remainingAttempts
     * @param  int|null $retryAfter
     * @return \Illuminate\Http\Response
     */
    protected function addHeaders(Response $response, $maxAttempts, $remainingAttempts, $retryAfter = null)
    {
        $headers = [
            'X-RateLimit-Limit' => $maxAttempts,
            'X-RateLimit-Remaining' => $remainingAttempts,
        ];
        if (!is_null($retryAfter)) {
            $headers['Retry-After'] = $retryAfter;
            $headers['Content-Type'] = 'application/json';
        }
        $response->headers->add($headers);
        return $response;
    }
    /**
     * Calculate the number of remaining attempts.
     *
     * @param  string $key
     * @param  int $maxAttempts
     * @param  int|null $retryAfter
     * @return int
     */
    protected function calculateRemainingAttempts($key, $maxAttempts, $retryAfter = null)
    {
        if (!is_null($retryAfter)) {
            return 0;
        }
        return $this->limiter->retriesLeft($key, $maxAttempts);
    }
}

然后将app/Http/Kernel.php文件里的:

'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,

替换成:

'throttle' => \App\Http\Middleware\ThrottleRequests::class,

编程笔记 » Throttle中间件怎么用?Laravel请求频率限制示例

赞同 (105) or 分享 (0)
游客 发表我的评论   换个身份
取消评论

表情
(0)个小伙伴在吐槽