import threading import queue import time from collections import deque class RateLimiter: def __init__(self, max_rate, time_window): self.max_rate = max_rate # 最大允许的请求数 self.time_window = time_window # 时间窗口(秒) self.timestamps = deque() self.lock = threading.Lock() def allow_request(self): with self.lock: current_time = time.time() # 移除超出时间窗口的时间戳 while self.timestamps and current_time - self.timestamps[0] > self.time_window: self.timestamps.popleft() if len(self.timestamps) < self.max_rate: self.timestamps.append(current_time) return True return False