zoukankan      html  css  js  c++  java
  • 16.熔断器使用(2):服务降级的使用

    使用熔断器降级,商品查询出错,降级使用系统推荐的商品

    package Weblib
    
    import (
        "github.com/afex/hystrix-go/hystrix"
        "github.com/gin-gonic/gin"
        "go-micro/Services"
        "strconv"
    )
    
    func newProd(id int32, pname string) *Services.ProdModel {
        return &Services.ProdModel{ProdID: id, ProdName: pname}
    }
    
    func defaultProds() (*Services.ProdListResponse, error) { //降级业务逻辑,应该尽量简单,保证不占用系统资源
        models := make([]*Services.ProdModel, 0)
        var i int32
        for i = 0; i < 5; i++ {
            models = append(models, newProd(100+i, "prodname"+strconv.Itoa(100+int(i))))
        }
        res := &Services.ProdListResponse{}
        res.Data = models
        return res, nil
    }
    
    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
            }, func(e error) error {
                //传入的参数e当服务超时的时候会被传入,还有服务执行报错的时候也会被传入,上述两种情况系统就使用推荐商品返回给客户
                prodRes, err = defaultProds()
                return err
            }) //第二个func是业务代码执行函数,第三个nil是降级函数,不采用降级可以传入nil
    
            if err != nil {
                ctx.JSON(500, gin.H{"status": err.Error()})
            }
            ctx.JSON(200, gin.H{"data": prodRes.Data})
        }
    }
    




  • 相关阅读:
    flutter setInitialRoute: 不生效
    mac os Catalina beta andriod studio crash
    Flutter 集成到现有iOS工程
    理解git
    selenium(一)--selenium 家族
    异常(一)
    java设计模式--创建型模式(一)
    理解JAVA虚拟机(下)
    mockito框架
    三次握手与四次释放
  • 原文地址:https://www.cnblogs.com/hualou/p/12132251.html
Copyright © 2011-2022 走看看