一. 创建熔断Wrappers中间键。
package Wrappersimport (\"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 int32for 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}}//Wrappertype 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()//第一步,配置configconfigA := hystrix.CommandConfig{Timeout: 1000,}//第二步,配置commandhystrix.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 mainimport (\"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),//在这里使用熔断Wrappermicro.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),运行,结果如下: