一. 建立熔斷Wrappers中間鍵。
package Wrappers
import (
"github.com/micro/go-micro/client"
"context"
"github.com/afex/hystrix-go/hystrix"
"go-micro-grpc/Services"
"strconv"
)
//熔斷後預設方法
func defaultProds(rsp interface{}) {
models := make([]*Services.ProdModel, 0)
var i int32
for i=0;i<5;i++{
models = append(models, newProd(20+i,"prodname"+strconv.Itoa(20+int(i))))
}
result := rsp.(*Services.ProdListResponse)
result.Data = models
}
func newProd(id int32,pname string) *Services.ProdModel{
return &Services.ProdModel{ProdID:id, ProdName:pname}
}
//Wrapper
type ProdsWrapper struct {
client.Client
}
//Wrapper方法
func (this *ProdsWrapper)Call(ctx context.Context, req client.Request, rsp interface{}, opts ...client.CallOption) error{
//command名稱
cmdName := req.Service()+"."+req.Endpoint()
//第一步,配置config
configA := hystrix.CommandConfig{
Timeout: 1000,
}
//第二步,配置command
hystrix.ConfigureCommand(cmdName, configA)
//第三部,執行,使用Do方法
return hystrix.Do(cmdName, func() error{
//如果正常,繼續執行
return this.Client.Call(ctx, req, rsp)
},func(e error) error{
//如果熔斷了,調用預設函數
defaultProds(rsp)
return nil
})
}
//Wrapper執行個體化
func NewProdsWrapper(c client.Client) client.Client{
return &ProdsWrapper{c}
}
二. 使用Wrapper。
package main
import (
"github.com/micro/go-plugins/registry/consul"
"github.com/micro/go-micro/registry"
"github.com/micro/go-micro/web"
"github.com/micro/go-micro"
"go-micro-grpc/Services"
"log"
"go-micro-grpc/Weblib"
"go-micro-grpc/Wrappers"
)
func main(){
//consul注冊中心
consulReg := consul.NewRegistry(
registry.Addrs("192.168.56.10:8500"),
)
myService := micro.NewService(
micro.Name("prodservice.client"),
micro.WrapClient(Wrappers.NewLogWrapper),
//在這裡使用熔斷Wrapper
micro.WrapClient(Wrappers.NewProdsWrapper),
)
prodService := Services.NewProdService("prodservice", myService.Client())
//建立web伺服器
httpServer := web.NewService(
web.Name("httpprodservice"), // 服務名
web.Address(":8001"), //端口号
web.Handler(Weblib.NewGinRouter(prodService)), // 路由
web.Registry(consulReg), // 注冊服務
)
//初始化伺服器
httpServer.Init()
//運作
err := httpServer.Run()
if err != nil{
log.Panic(err)
}
}
三. 測試熔斷。
熔斷前,正常調用:
我在服務端handler方法裡面加入time.Sleep(time.Second*5),運作,結果如下:
補充:
有三個參數記一下
hystrix.CommandConfig{
Timeout: 1000,
//預設20 。熔斷器請求閥值,意思是有20個請求才進行 錯誤百分比計算
RequestVolumeThreshold:20,
//就是錯誤百分比。預設50(50%)
ErrorPercentThreshold:50,
//過多長時間,熔斷器再次檢測是否開啟。機關毫秒 (預設5秒)
SleepWindow :5000,
}
這配置的意思是有2個請求進來,其中一半發生錯誤,則開啟熔斷器,開啟時長為5秒(即一開始就調用降級方法,不走真實方法)。