gobreakerソース分析ノート
2351 ワード
ソニー大法オープンソースヒューズhttps://github.com/sony/gobreaker
Microsoft Circuit Breaker patternベース
3つの状態
基本構成
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 //
}
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
}
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
}
}