• 15.熔断器使用(1):hystrix初步、捕获超时报错


    现在rpc服务端设置3秒延迟模拟

    package ServiceImpl
    
    import (
        "context"
        "go-micro-grpc/Services"
        "strconv"
        "time"
    )
    
    type ProdService struct {
    }
    
    func (*ProdService) GetProdsList(ctx context.Context, in *Services.ProdsRequest, res *Services.ProdListResponse) error {
        time.Sleep(time.Second * 3) //设置3秒延迟
        ret := make([]*Services.ProdModel, 0)
        var i int32
        for i = 0; i < in.Size; i++ {
            ret = append(ret, newProd(100+i, "prodname"+strconv.Itoa(100+int(i))))
        }
        res.Data = ret
        return nil
    }
    
    func newProd(id int32, pname string) *Services.ProdModel {
        return &Services.ProdModel{ProdID: id, ProdName: pname}
    }
    

    使用hystrix熔断器

    package Weblib
    
    import (
        "github.com/afex/hystrix-go/hystrix"
        "github.com/gin-gonic/gin"
        "go-micro/Services"
    )
    
    func GetProdsList(ctx *gin.Context) {
        var prodReq Services.ProdsRequest
        prodservice := ctx.Keys["prodservice"].(Services.ProdService) //类型断言之前通过中间件封装到ctx中的prodService
        err := ctx.Bind(&prodReq)
        if err != nil {
            ctx.JSON(500, gin.H{"status": err.Error()})
        } else {
            //熔断代码改造
            //第一步,配置config
            configA := hystrix.CommandConfig{
                Timeout: 1000, //允许延迟一秒
            }
            //第二部,配置command
            hystrix.ConfigureCommand("getprods", configA)
            //执行使用Do方法
            var prodRes *Services.ProdListResponse
            err := hystrix.Do("getprods", func() error {
                prodRes, err = prodservice.GetProdsList(ctx, &prodReq)
                return err
            }, nil) //第二个func是业务代码执行函数,第三个nil是降级函数,不采用降级可以传入nil
    
            if err != nil {
                ctx.JSON(500, gin.H{"status": err.Error()})
            }
            ctx.JSON(200, gin.H{"data": prodRes.Data})
        }
    }
    

    因为我们设置的熔断器允许的延迟是一秒,而服务端我们设置了3秒延迟,所以这里很明显,会报错,返回值如下





  • 相关阅读:
    HTTP 状态码大全
    Redis Cluster数据分片机制
    redis 哨兵集群原理及部署
    python 连接 redis cluster 集群
    python连接redis哨兵集群
    Ubuntu设置终端操作行为的回收站
    实用Golang库
    实用的Python库
    Python 生成 JWT(json web token) 及 解析方式
    django 进行语言的国际化及在后台进行中英文切换
  • 原文地址:https://www.cnblogs.com/hualou/p/12131967.html
Copyright © 2020-2023  润新知