码迷,mamicode.com
首页 > 其他好文 > 详细

20.超时情况下的服务降级写法

时间:2019-12-23 16:39:41      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:tom   play   写法   UNC   pac   package   none   git   string   

技术图片

在hystrix的超时回调函数中处理超时推荐其他商品

package main

import (
    "errors"
    "fmt"
    "github.com/afex/hystrix-go/hystrix"
    "math/rand"
    "time"
)

type Product struct {
    ID    int
    Title string
    Price int
}

func getProduct() (Product, error) {
    r := rand.Intn(10)
    if r < 6 { //模拟api卡顿和超时效果
        time.Sleep(time.Second * 4)
    }
    return Product{
        ID:    101,
        Title: "Golang从入门到精通",
        Price: 12,
    }, nil
}

func RecProduct() (Product, error) {
    return Product{
        ID:    999,
        Title: "推荐商品",
        Price: 120,
    }, nil

}

func main() {
    rand.Seed(time.Now().UnixNano())
    configA := hystrix.CommandConfig{ //创建一个hystrix的config
        Timeout: 3000, //command运行超过3秒就会报超时错误
    }
    hystrix.ConfigureCommand("get_prod", configA) //hystrix绑定command
    for {
        err := hystrix.Do("get_prod", func() error { //使用hystrix来讲我们的操作封装成command
            p, _ := getProduct() //这里会随机延迟0-4秒
            fmt.Println(p)
            return nil
        }, func(e error) error {
            fmt.Println(RecProduct()) //超时后调用回调函数返回推荐商品
            return errors.New("my timeout")
        })
        if err != nil {
            //如果降级也失败了,在这里定义业务逻辑
        }
    }
}




20.超时情况下的服务降级写法

标签:tom   play   写法   UNC   pac   package   none   git   string   

原文地址:https://www.cnblogs.com/hualou/p/12084189.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!