getClientIp(); $maxRequestsPerSecond = $this->maxRequestsPerSecond; // 使用 Redis 存储每秒请求的计数,键的格式:qps:{IP}:{timestamp_second} $redisKey = 'qps:' . $ip . ':' . now()->timestamp; // Redis 的计数器操作:INCR命令返回自增后的值 $requests = Redis::incr($redisKey); // 如果是第一次请求,设置过期时间为1秒 if ($requests === 1) { Redis::expire($redisKey, 1); } // 判断当前秒内请求数是否超过限制 if ($requests > $maxRequestsPerSecond) { BlackList::addIp($ip); return response()->json([ 'code' => 0, 'msg' => '请求频繁' ], Response::HTTP_TOO_MANY_REQUESTS); } return $next($request); } }