通过故障经验解析熔断器 (Circuit Breaker)
几天前,我遇到了一个意想不到的问题。
挫败感让我倍感压力。我想修复它。好奇心驱使我不断探索。
我再次坐下来研究这个问题。我找到了解决方案。它被称为熔断器(Circuit Breaker)。
在软件中,熔断器可以防止单个故障导致整个系统崩溃。它的工作原理就像你家里的断路器一样。
熔断器有三种状态:
- CLOSED(闭合):一切正常。所有请求都能通过。系统会追踪失败次数。如果失败次数达到限制,电路将变为 OPEN。
- OPEN(断开):系统立即停止所有请求。这为故障服务提供了恢复的时间。
- HALF_OPEN(半开):系统允许少量测试请求。如果成功,电路闭合;如果失败,电路再次断开。
以下是一个简单的代码实现:
export class CircuitBreaker {
constructor(failureThreshold, cooldownMs) {
this.failureThreshold = failureThreshold
this.cooldownMs = cooldownMs
this.state = "CLOSED"
this.failureCount = 0
this.lastFailureTime = null
}
openCircuit() {
this.state = "OPEN"
this.lastFailureTime = Date.now()
}
closeCircuit() {
this.state = "CLOSED"
this.failureCount = 0
this.lastFailureTime = null
}
halfOpenCircuit() {
this.state = "HALF_OPEN"
}
async execute(fn) {
if (this.state === "OPEN") {
const cooldownExpired = Date.now() - this.lastFailureTime >= this.cooldownMs
if (!cooldownExpired) {
throw new Error("Circuit is open.")
}
this.halfOpenCircuit();
}
try {
const result = await fn()
if (this.state === "HALF_OPEN") {
this.closeCircuit()
}
return result;
} catch (error) {
if (this.state === "HALF_OPEN") {
this.openCircuit()
throw error;
}
this.failureCount++
if (this.failureCount >= this.failureThreshold) {
this.openCircuit()
}
throw error
}
}
}
这个机制解决了我的近期问题。它能防止错误洪流摧毁你的应用程序。
请在评论区分享你的看法。我仍在学习中。
来源:https://dev.to/neel-vekariya/circuit-breaker-explained-through-real-failure-experience-3aeg