DEV Community

drake
drake

Posted on Edited on

算法题:令牌桶限流器

from threading import Lock
import time

class Bucket:
    def __init__(self, capacity: float, rate: float):
        self.capacity = capacity
        self.rate = rate
        self.tokens = capacity
        self.last_refill = time.time()
        self.lock = Lock()

    def allow_request(self, url: str) -> bool:
        with self.lock:
            now = time.time()
            elapsed = now - self.last_refill
            tokens_to_add = int(elapsed * self.rate)
            self.tokens = min(self.tokens + tokens_to_add, self.capacity)
            self.last_refill = now
            if self.tokens > 0:
                self.tokens -= 1
                return True
            return False


Enter fullscreen mode Exit fullscreen mode

Top comments (0)