示例说明
实现类型化熔断器状态机,带关闭、打开、半开转换和指标。本示例属于弹性容错场景,提供可直接复制使用的typescript代码片段,附带边界条件与使用注意事项。
技术要点
- 三态转换 closed open half-open
- half-open 成功转 closed 失败转 open
- getState 暴露状态用于监控
代码解读
上述代码实现了类型化熔断器状态机的核心逻辑。实现类型化熔断器状态机,带关闭、打开、半开转换和指标。代码中包含输入校验、核心算法和结果返回三个部分。关键在于正确处理边界情况,例如空输入、非法参数和并发场景。三态转换 closed open half-open,half-open 成功转 closed 失败转 open。这些设计确保代码在生产环境中的健壮性。
使用建议
在实际项目中使用本示例时,建议先理解类型化熔断器状态机的适用场景与限制条件。getState 暴露状态用于监控。根据具体业务需求调整参数配置,并编写单元测试覆盖正常路径与边界情况。本代码片段可直接集成到现有项目中,或作为参考实现自行扩展。
代码示例
type State='closed'|'open'|'half-open';export class CircuitBreaker{private state:State='closed';private failures=0;private lastFailure=0;constructor(private fn:Function,private opts:{threshold:number;resetMs:number}){}async call<T>(...args:any[]):Promise<T>{if(this.state==='open'&&Date.now()-this.lastFailure<this.opts.resetMs)throw new Error('open');if(this.state==='open')this.state='half-open';try{const r=await this.fn(...args);if(this.state==='half-open'){this.state='closed';this.failures=0;}return r;}catch(e){this.failures++;this.lastFailure=Date.now();if(this.state==='half-open'||this.failures>=this.opts.threshold)this.state='open';throw e;}}getState():State{return this.state;}}