laravel5.2-第2章-限制访问次数 laravel5.2-第2章-限制访问次数

2023-06-29

一、实现

修改 app/Http/routes.php

Route::get('/user/{user}', function (\App\User $user) {
   return $user;
})->middleware('throttle:3');

这里的 3 表示一分钟内只允许请求 3 次

修改 app/Providers/RouteServiceProvider.php 的 boot 方法

public function boot(Router $router)
{
   parent::boot($router);
}

使用 curl 进行测试

curl http://localhost:8000/user/10

https://file.lulublog.cn/images/3/2023/06/Y9x6JDIrCI1BBYz4Myiyk49849IKa8.jpg

红色框中

  • X-RateLimit-Limit = 3 表示一分钟内只允许请求 3 次

  • X-RateLimit-Remaining = 2 表示一分钟内剩余请求 2 次

第四次 curl

https://file.lulublog.cn/images/3/2023/06/JnJJ7906zn70L630znPjmJ9j37Jbny.jpg

报错:Too Many Requests。

二、源码

访问 app/Http/Kernel.php,滑倒最后

https://file.lulublog.cn/images/3/2023/06/A48tM10Dn0D8rNTT1dwtR41PUNaPmA.jpg

点击 \Illuminate\Routing\Middleware\ThrottleRequests 跳转到这里类,查看 hadel 方法

https://file.lulublog.cn/images/3/2023/06/iOOSRg13rVB1Abidog1q6kZOg1k717.jpg

查看方法中的签名:resolveRequestSignature,跳转到 fingerprint 看到签名的方式

https://file.lulublog.cn/images/3/2023/06/q4481I2H888812928N2f2z271Rf588.jpg

查看 tooManyAttempts:对生成的签名进行缓存了,如果超过限制就会返回 true

https://file.lulublog.cn/images/3/2023/06/M30r37Z3713DNTotoTDRF7Z8IodNNl.jpg

通过 buildResponse 抛出异常

https://file.lulublog.cn/images/3/2023/06/i83i8hsNSPHEef8Fp6sIHw41A6eaP8.jpg

如果没有超过限制,就会通过 hit 方法加 1

https://file.lulublog.cn/images/3/2023/06/gGuVPU8Wur85PGu3NV62gw22uJGmG9.jpg

查看 addHeaders 方法,可以看到 X-RateLimit-Limit 和 X-RateLimit-Remaining

https://file.lulublog.cn/images/3/2023/06/m76I6kDkAhaDudTS8aDo8sHHuI4Idu.jpg

打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开微信扫一扫,即可进行扫码打赏哦

阅读 265