使用 laravel8 的 RateLimiter 对部分API做访问速率限制,记录了定义规则和在路由文件中使用。
定义速率限制规则,
在 app/Providers/RouteServiceProvider.php boot方法内定义,如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| use Illuminate\Support\Facades\RateLimiter; use Illuminate\Http\Request; use Illuminate\Cache\RateLimiting\Limit;
public function boot() { // 100/IP/24h RateLimiter::for('limitsec', function (Request $request) { $key = $_SERVER['REMOTE_ADDR']; if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $key = $_SERVER['HTTP_X_FORWARDED_FOR']; } $key .= $request->route()->uri; return Limit::perDay(100)->by($key)->response(function () { return response()->json([ 'code' => 500, 'message' => '操作触发速率限制,请稍后再试。', 'data' => "", ]); }); });
// ocr 50/IP/24h RateLimiter::for('limitocr', function (Request $request) { $key = $_SERVER['REMOTE_ADDR']; if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $key = $_SERVER['HTTP_X_FORWARDED_FOR']; } $key .= $request->route()->uri; return Limit::perDay(50)->by($key)->response(function () { return response()->json([ 'code' => 500, 'message' => '操作触发速率限制,请稍后再试。', 'data' => "", ]); }); });
parent::boot(); }
|
在路由中使用:
1
| Route::post('/api/ocr', 'Home\ApiController@ocr')->middleware(['throttle:limitocr']);
|
参考:
https://learnku.com/docs/laravel/8.x/routing/9365#5c3711
https://www.amitmerchant.com/new-ratelimiter-facade-in-laravel-8/