首先贴出仓库地址:https://github.com/JeffreyDing11223/goBreaker
这个熔断器实现简单,使用方便,同时大家也可以fork后进行自己需要的改造,当然,也欢迎大家提pr,一起优化goBreaker
下面介绍下goBreaker:
goBreaker状态机
状态转换逻辑
- 初始为closed状态,一旦遇到请求失败时,会触发熔断检测(见下方的 ShouldTrip),熔断检测来决定是否将状态从closed转为open。
- 当熔断器为open状态时,会熔断所有当前服务要发出去的请求,直到冷却时间(见下方的CoolingTimeout)结束,会从open转变为half-open状态。
- 当熔断器为half-open状态时,以检测时间(见下方的 DetectTimeout)为周期去发送请求。请求成功则计数器加1,当计数器达到一定阈值时则转为closed状态;请求失败则转为open状态。
熔断器内部数据结构
type Breaker struct {
Container // contains all success, error and timeout
sync.RWMutex
state State
openTime time.Time // the time when the breaker become OPEN
lastRetryTime time.Time // last retry time when in