熔斷器 Hystrix-go
hystrix-go是用go實作的hystrix版,提供了基礎的熔斷、降級功能,
專案中應用
完整代碼:
https://github.com/Justin02180218/micro-kit
在 pkg 下新建目錄 circuitbreakers,創建 hystrix.go 檔案:

代碼如下:
import "github.com/afex/hystrix-go/hystrix"
func Hystrix(commandName, fallbackMsg string) endpoint.Middleware {
return func(next endpoint.Endpoint) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (response interface{}, err error) {
err = hystrix.Do(
commandName,
// 熔斷開關
func() error {
response, err = next(ctx, request)
return err
},
// 降級
func(err error) error {
fmt.Println("fallbackErrorDesc", err.Error())
response = struct {
Fallback string `json:"fallback"`
}{fallbackMsg}
return nil
})
if err != nil {
return nil, err
}
return
}
}
}
在 go kit 的 endpoint 層進行限流,采用裝飾器模式,
我們在 user-service 微服務中呼叫 book-rpc-service 微服務的介面加入熔斷器:

組態檔
配置 hystrix 流資料介面,用于 hystrix-dashboard 收集資料,
hystrix:
stream_port: 9000
type HystrixConfig struct {
StreamPort string `json:"streamport" yaml:"streamport"`
}
修改 main.go
import "github.com/afex/hystrix-go/hystrix"
hystrix.ConfigureCommand("Find books", hystrix.CommandConfig{Timeout: 1000})
grpcClient = circuitbreakers.Hystrix("Find books", "book-rpc-service currently unavailable")(grpcClient)
hystrixStreamStreamHandler := hystrix.NewStreamHandler()
hystrixStreamStreamHandler.Start()
go func() {
errChan <- http.ListenAndServe(net.JoinHostPort("", configs.Conf.HystrixConfig.StreamPort), hystrixStreamStreamHandler)
}()
啟動 hystrix-dashboard
使用 Docker 啟動 hystrix-dashboard:
docker pull mlabouardy/hystrix-dashboard
docker run -p 8181:9002 --name hystrix-dashboard mlabouardy/hystrix-dashboard:latest
在瀏覽器地址欄輸入:http://localhost:8181/hystrix 查看介面請求資訊
測驗
啟動 user-service 微服務,但是不啟動 book-rpc-service 微服務,介面快速回傳熔斷降級資訊:

啟動 book-rpc-service 微服務,介面回傳書籍串列:

下一篇文章,我們基于Consul寫一個簡單的網關服務(library-apigateway),
完整代碼:
https://github.com/Justin02180218/micro-kit
更多【分布式專輯】【架構實戰專輯】系列文章,請關注公眾號

轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/304497.html
標籤:其他
