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

21.异步执行和服务降级

时间:2019-12-23 16:42:57      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:imp   ott   top   模拟   title   ice   man   创建   sele   

异步执行和服务降级,使用hystrix.Go()函数的返回值是chan err

package main

import (
    "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
    resultChan := make(chan Product, 1)
    for {
        errs := hystrix.Go("get_prod", func() error { //使用hystrix来讲我们的操作封装成command,hystrix返回值是一个chan error
            p, _ := getProduct() //这里会随机延迟0-4秒
            resultChan <- p
            return nil //这里返回的error在回调中可以获取到,也就是下面的e变量
        }, func(e error) error {
            rcp, err := RecProduct() //推荐商品,如果这里的err不是nil,那么就会忘errs中写入这个err,下面的select就可以监控到
            resultChan <- rcp
            return err
        })
        select {
        case getProd := <-resultChan:
            fmt.Println(getProd)
        case err := <-errs: //使用hystrix.Go时返回值是chan error各个协程的错误都放到errs中
            fmt.Println(err,1)
        }
    }
}




21.异步执行和服务降级

标签:imp   ott   top   模拟   title   ice   man   创建   sele   

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

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