You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
23 lines
768 B
23 lines
768 B
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
|