索尼大法开源熔断器 https://github.com/sony/gobreaker
基于微软Circuit Breaker pattern
三种状态
- Closed
- Open
- HalfOpen
基本配置
type Settings struct {
Name string //breaker名称
MaxRequests uint32 // 最大请求数,用于HelfOpen状态
Interval time.Duration // Close状态时,定期清除counts
Timeout time.Duration // Open状态timeout后,进入HelfOpen
ReadyToTrip func(counts Counts) bool // Closed状态时,当报错时调用它。当连续错误达到一定数量时,进入Open状态
OnStateChange func(name string, from State, to State) // 状态变化时调用
}
Counts 结构体
范围: Generation周期内
type Counts struct {
Requests uint32 //请求次数
TotalSuccesses uint32 // 总共成功次数
TotalFailures uint32 // 总共失败次数
ConsecutiveSuccesses uint32 // 连续成功次数
ConsecutiveFailures uint32 // 连续失败次数
}
toNewGeneration: 生成新的generation。 主要是清空counts和设置expiry(过期时间)。当状态为Closed时expiry为Closed的过期时间(当前时间 + interval),当状态为Open时expiry为Open的过期时间(当前时间 + timeout)
currentState: 获取当前状态。当Closed时且expiry过期,调用toNewGeneration生成新的generation。当Open时且expiry过期,设为helfOpen。
核心执行函数Execute: 该函数分为三步 beforeRequest、 执行请求、 afterRequest
func (cb *CircuitBreaker) Execute(req func() (interface{}, error)) (interface{}, error) {
generation, err := cb.beforeRequest()
if err != nil {
return nil, err
}
defer func() {
e := recover()
if e != nil {
cb.afterRequest(generation, false)
panic(e)
}
}()
result, err := req()
cb.afterRequest(generation, err == nil)
return result, err
}
- beforeRequest: 通过currentState获取状态,当为Open时,直接返回错误。当为HelfOpen时,且counts里面的请求数量大于等于maxRequests时,返回错误。否则counts的Requests加1
- req: 获取请求结果
- afterRequest:
func (cb *CircuitBreaker) afterRequest(before uint64, success bool) {
cb.mutex.Lock()
defer cb.mutex.Unlock()
now := time.Now()
state, generation := cb.currentState(now)
if generation != before {
return
}
if success {
cb.onSuccess(state, now) // 修改counts
} else {
cb.onFailure(state, now) // Closed: 如果readyToTrip,则变为Open。HelfOpen:变为Open
}
}