您的位置:首页 > 编程语言 > Go语言

go-micro学习日记(四)--熔断

2020-08-06 15:32 1041 查看

一. 创建熔断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),运行,结果如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: