掃二維碼與項目經理溝通
我們在微信上24小時期待你的聲音
解答本文疑問/技術咨詢/運營咨詢/技術建議/互聯網交流
一些場景下,為了保障服務穩(wěn)定性會引入熔斷機制。本文介紹了用 Go 語言自己實現熔斷需要什么操作。

成都創(chuàng)新互聯公司自2013年創(chuàng)立以來,先為德清等服務建站,德清等地企業(yè),進行企業(yè)商務咨詢服務。為德清企業(yè)網站制作PC+手機+微官網三網同步一站式服務解決您的所有建站問題。
熔斷是指在下游發(fā)生錯誤時上游主動關閉或限制對下游的請求。
總得來說三個狀態(tài)的轉換大致如下圖:
https://github.com/rubyist/circuitbreaker
CLOSE 允許
OPEN
HALFOPEN
atomic.StoreInt32((*int32)(&b.state), int32(HALFOPEN))
- type TripFunc func(Metricser) bool
- type Metricser interface {
- Fail() // records a failure
- Succeed() // records a success
- Timeout() // records a timeout
- Failures() int64 // return the number of failures
- Successes() int64 // return the number of successes
- Timeouts() int64 // return the number of timeouts
- ConseErrors() int64 // return the consecutive errors recently
- ErrorRate() float64 // rate = (timeouts + failures) / (timeouts + failures + successes)
- Samples() int64 // (timeouts + failures + successes)
- Counts() (successes, failures, timeouts int64)
- Reset()
- }
window 實現類
- type window struct {
- sync.RWMutex
- oldest int32 // oldest bucket index
- latest int32 // latest bucket index
- buckets []bucket // buckets this window holds
- bucketTime time.Duration // time each bucket holds
- bucketNums int32 // the numbe of buckets
- inWindow int32 // the number of buckets in the window
- allSuccess int64
- allFailure int64
- allTimeout int64
- conseErr int64
- }
- type bucket struct {
- failure int64
- success int64
- timeout int64
- }
用環(huán)形隊列實現動態(tài)統(tǒng)計。把一個連續(xù)的時間切成多個小份,每一個 bucket 保存 BucketTime 的統(tǒng)計數據,BucketTime * BucketNums 是統(tǒng)計的時間區(qū)間。
每 BucketTime,會有一個 bucket 過期
- if w.inWindow == w.bucketNums {
- // the lastest covered the oldest(latest == oldest)
- oldBucket := &w.buckets[w.oldest]
- atomic.AddInt64(&w.allSuccess, -oldBucket.Successes())
- atomic.AddInt64(&w.allFailure, -oldBucket.Failures())
- atomic.AddInt64(&w.allTimeout, -oldBucket.Timeouts())
- w.oldest++
- if w.oldest >= w.bucketNums {
- w.oldest = 0
- }
- } else {
- w.inWindow++
- }
- w.latest++
- if w.latest >= w.bucketNums {
- w.latest = 0
- }
- (&w.buckets[w.latest]).Reset()
- type PanelStateChangeHandler func(key string, oldState, newState State, m Metricser)

我們在微信上24小時期待你的聲音
解答本文疑問/技術咨詢/運營咨詢/技術建議/互聯網交流