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

一. 创建熔断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秒(即一开始就调用降级方法,不走真实方法)。

猜你喜欢

转载自blog.csdn.net/qq_36453564/article/details/107840862