ARTICLE DETAIL
日记详情
真实记录编程学习的某一天,欢迎挑你感兴趣的翻一翻。
真实记录编程学习的某一天,欢迎挑你感兴趣的翻一翻。
pythonimport timeclass TimeoutBudget: def __init__(self, deadline_ms): self.deadline = time.time() * 1000 + deadline_ms def remaining(self): return max(0, int(self.deadline - time.time() * 1000)) def allocate(self, ratio): return int(self.remaining() * ratio)budget = TimeoutBudget(8000)for name, ratio in [("inventory", 0.3), ("promo", 0.25), ("logistics", 0.2), ("lock", 0.25)]: print(f"{name}: {budget.allocate(ratio)}ms")💡 关键是动态读取剩余预算。某步超预期,后续立即收缩窗口,而不是按固定值执行。这种机制让整条链路具备弹性,而不是在第一步就提前宣告死亡。## 四、Circuit Breaker 嵌入🔒 当错误率超阈值,主动断开避免无效等待:pythonclass CircuitBreaker: def __init__(self, threshold=5, cooldown=10): self.threshold = threshold self.cooldown = cooldown self.failures = 0 self.open = False self.last_fail = 0 def call(self, fn, *args, **kwargs): if self.open: if time.time() - self.last_fail > self.cooldown: self.open = False else: raise RuntimeError("circuit open") try: return fn(*args, **kwargs) except Exception: self.failures += 1 self.last_fail = time.time() if self.failures >= self.threshold: self.open = True raise