Hystrix使用

package main

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

func main() {
    rand.NewSource(time.Now().UnixNano())
    configA := hystrix.CommandConfig{
        Timeout:                1000,
        MaxConcurrentRequests:  5,
        RequestVolumeThreshold: 5,
        ErrorPercentThreshold:  50,
        SleepWindow:            5000,
    }
    hystrix.ConfigureCommand("get product", configA)
    for {
        time.Sleep(1 * time.Second)
        errs := hystrix.Do("get product", func() error {
            p := getProduct()
            fmt.Println(p)
            return nil
        }, func(err error) error {
            p := getDefaultProduct()
            fmt.Println(p)
            return errors.New("get product error")
        })
        if errs != nil {
            fmt.Println(errs)
        }
    }
}

type Product struct {
    ID    int
    Title string
    Price int
}

func getDefaultProduct() Product {
    return Product{
        ID:    101,
        Title: "default product",
        Price: 100,
    }
}

func getProduct() Product {
    r := rand.Intn(10)
    if r < 6 {
        time.Sleep(time.Second * 3)
    }
    return Product{
        ID:    101,
        Title: "product",
        Price: 100,
    }
}

results matching ""

    No results matching ""