例如:我希望每15分钟允许500个请求(来自任何已登录用户的请求)的API路由
* API速率限制将在15分钟后重置
如何做这样的事情?
答案 0 :(得分:0)
向数据库中的用户表添加limit
和limit_created_at
列,并使用类似的代码创建中间件:
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class AuthLimitMiddleware
{
public function handle($request, Closure $next, $guard = null)
{
$user = Auth::user(); //or your get user method
DB::table('users')->where('id', $user->id)->increment('limit');
if ($user->limit_created_at + 60 * 15 > time()) {
$user->limit = 0;
$user->limit_craeted_at = now();
$user->save();
}
if ($user->limit > 500) {
throw new ConflictHttpException('limit is more for 500')
}
return $next($request);
}
}
现在在内核文件中注册中间件:
protected $routeMiddleware = [
...
'limit' => \App\Http\Middleware\AuthLimitMiddleware::class,
];
并在路线上使用它:
Route::get('some/route')->middleware('auth', 'limit');