import logging 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.lock = threading.Lock() self.current_time = time.time() self.interval = time_window / max_rate if max_rate > 0 else 0 self.next_available_time = self.current_time def update_interval(self): self.interval = self.time_window / self.max_rate if self.max_rate > 0 else 0 def allow_request(self): with self.lock: if self.interval<=0: return False current_time = time.time() if current_time >= self.next_available_time: self.next_available_time = current_time + self.interval #logging.info(f"rate[{self.max_rate}]下次请求 now={current_time} < {self.next_available_time}") return True #logging.info(f"rate[{self.max_rate}]不准请求 now={current_time} < {self.next_available_time}") return False