首页 > 其他 > 详细

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

时间:2020-01-02 12:59:18      阅读:89      评论:0      收藏:0      [点我收藏+]

技术分享图片

技术分享图片

现在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秒延迟,所以这里很明显,会报错,返回值如下

技术分享图片





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

原文:https://www.cnblogs.com/hualou/p/12131967.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!