github完整代碼地址 我的博客git
hystrix是Netflix開源的一個JAVA項目,不過GitHub也有golang的實現版本hystrix-gogithub
hystrix並無自帶一個儀表盤,沒法直觀的查看接口的健康情況。因此,咱們採用GitHub的一個開源實現hystrix-dashboard。golang
docker run --name hystrix-dashboard -d -p 8081:9002 mlabouardy/hystrix-dashboard:latest
複製代碼
關於hystrix的工做原理,能夠查閱相關資料,這裏只講解如何封裝插件在micro API網關中使用。docker
err := hystrix.Do("my_command", func() error {
// talk to other services
return nil
}, nil)
複製代碼
使用hystrix.Do() 同步API,第一個參數是command, 應該是與當前請求一一對應的一個名稱,如入「GET-/test」。第二個參數傳入一個函數,函數包含我咱們本身的錯誤邏輯,當請求失敗時應該返回error。hystrix會根據咱們的失敗率執行熔斷策略。bash
// BreakerWrapper hystrix breaker
func BreakerWrapper(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
name := r.Method + "-" + r.RequestURI
log.Println(name)
err := hystrix.Do(name, func() error {
sct := &status_code.StatusCodeTracker{ResponseWriter: w, Status: http.StatusOK}
h.ServeHTTP(sct.WrappedResponseWriter(), r)
if sct.Status >= http.StatusBadRequest {
str := fmt.Sprintf("status code %d", sct.Status)
log.Println(str)
return errors.New(str)
}
return nil
}, nil)
if err != nil {
log.Println("hystrix breaker err: ", err)
return
}
})
}
...
// 註冊插件
plugin.Register(plugin.NewPlugin(
plugin.WithName("breaker"),
plugin.WithHandler(
hystrix.BreakerWrapper,
),
))
...
複製代碼
在 hystrix.Do 中,首先執行 h.ServeHTTP,該函數返回後,即請求執行完成。咱們判斷HTTP狀態碼,若是大於StatusBadRequest,則認爲此次請求失敗,返回一個錯誤,hystrix會收集錯誤,若是錯誤率達到某個閥值,就會觸發斷路器。 在作實驗時,能夠直接在main函數裏設置hystrix的幾個默認配置參數,方便看效果app
// hystrix-go/hystrix/settings.go
// DefaultTimeout is how long to wait for command to complete, in milliseconds
DefaultTimeout = 1000
// DefaultMaxConcurrent is how many commands of the same type can run at the same time
DefaultMaxConcurrent = 10
// DefaultVolumeThreshold is the minimum number of requests needed before a circuit can be tripped due to health
DefaultVolumeThreshold = 20
// DefaultSleepWindow is how long, in milliseconds, to wait after a circuit opens before testing for recovery
DefaultSleepWindow = 5000
// DefaultErrorPercentThreshold causes circuits to open once the rolling measure of errors exceeds this percent of requests
DefaultErrorPercentThreshold = 50
複製代碼
hystrix-go庫還提供爲每一個commond動態設置配置的接口,咱們能夠經過這個接口結合配置中心,動態調節服務。函數
hystrix.ConfigureCommand("my_command", hystrix.CommandConfig{
Timeout: 1000,
MaxConcurrentRequests: 100,
ErrorPercentThreshold: 25,
})
複製代碼
docker run --name hystrix-dashboard -d -p 8081:9002 mlabouardy/hystrix-dashboard:latest
複製代碼
打開 http://localhost:8081/hystrix , 輸入 http://{ip}:81/hystrix.stream , 此處ip爲本機ip,由於hystrix-dashboard是容器啓動的,沒法直接訪問本機127.0.0.1。post
Enable dashboard metrics In your main.go, register the event stream HTTP handler on a port and launch it in a goroutine. Once you configure turbine for your Hystrix Dashboard to start streaming events, your commands will automatically begin appearing.ui
hystrixStreamHandler := hystrix.NewStreamHandler()
hystrixStreamHandler.Start()
go http.ListenAndServe(net.JoinHostPort("", "81"), hystrixStreamHandler)
複製代碼
項目完整
代碼地址