基于hytrix-go的熔断器 #
流量限制,熔断器,服务降级
1. 代码示例 #
package main
import (
"errors"
"github.com/afex/hystrix-go/hystrix"
"log"
"net/http"
"time"
)
func main() {
hystrixStreamHandler := hystrix.NewStreamHandler()
hystrixStreamHandler.Start()
go http.ListenAndServe(":8074", hystrixStreamHandler)
hystrix.ConfigureCommand("aaa", hystrix.CommandConfig{
Timeout: 1000, // 单次请求 超时时间
MaxConcurrentRequests: 1, // 最大并发量
SleepWindow: 5000, // 熔断后多久去尝试服务是否可用
RequestVolumeThreshold: 1,
ErrorPercentThreshold: 1,
})
for i := 0; i < 10000; i++ {
//异步调用使用 hystrix.Go
err := hystrix.Do("aaa", func() error {
//test case 1 并发测试
if i == 0 {
return errors.New("service error")
}
//test case 2 超时测试
//time.Sleep(2 * time.Second)
log.Println("do services")
return nil
}, nil)
if err != nil {
log.Println("hystrix err:" + err.Error())
time.Sleep(1 * time.Second)
log.Println("sleep 1 second")
}
}
time.Sleep(100 * time.Second)
}
Timeout
单次请求的超时时间,超时进fallbackMaxConcurrentRequests
最大并发量,这里是并发,并非QPSSleepWindow
熔断后sleep多久再次尝试服务是否可用RequestVolumeThreshold
判断熔断的最少请求数,默认是10;只有在一个统计窗口内处理的请求数量达到这个阈值,才会进行熔断与否的判断ErrorPercentThreshold
错误百分比达到多少触发熔断