maxRequests = $maxRequests; $this->windowSeconds = $windowSeconds; $this->prefix = $prefix; } public function handle(array $request, callable $next): mixed { $ip = md5(clientIp()); $key = "rate_limit:{$this->prefix}:{$ip}"; $now = time(); $window = $now - $this->windowSeconds; $cacheDir = STORAGE_PATH . '/cache'; if (!is_dir($cacheDir)) { mkdir($cacheDir, 0755, true); } $cacheFile = $cacheDir . '/rate_limit.json'; $data = []; if (file_exists($cacheFile)) { $data = json_decode(file_get_contents($cacheFile), true) ?: []; } // 清理过期记录 if (!isset($data[$key])) { $data[$key] = []; } $data[$key] = array_filter($data[$key], fn($t) => $t > $window); if (count($data[$key]) >= $this->maxRequests) { Application::jsonResponse(429, '请求过于频繁,请稍后再试', null, 429); } $data[$key][] = $now; file_put_contents($cacheFile, json_encode($data), LOCK_EX); return $next($request); } }