断路器的相关原理可参考:https://skaygo.blog.youkuaiyun.com/article/details/110442898
hystrix-go的源码地址:https://github.com/afex/hystrix-go
下载:go get github.com/afex/hystrix-go/hystrix
开启一个简单的http服务svc
请求 /hello 会返回 hello,world
相关代码如下(svc.go):
package main
import (
"io"
"log"
"net/http"
)
func main() {
http.HandleFunc("/hello",helloServer)
log.Fatal(http.ListenAndServe(":18080",nil))
}
func helloServer(w http.ResponseWriter, req *http.Request) {
log.Println("request remote addr",req.RemoteAddr)
io.WriteString(w, "hello,world")
}
go run svc.go
运行之后浏览器中请求

http客户端client使用断路器hystrix
相关代码如下(client.go):
package main
import (
"log"
"time"
"errors"
"io/ioutil"
"net/http"
"github.com/afex/hystrix-go/hystrix"
)
func main() {
httpURL := "http://localhost:18080/hello"
//初始化hystrix配置
hystrix.ConfigureCommand("svc1", hystrix.CommandConfig{
MaxConcurrentRequests : 5, //设置请求的并发数量
RequestVolumeThreshold : 4, //配置断路器断开需要的最少请求失败数量
})
for i := 0 ; i < 10 ; i++ {
for j := 0 ; j< 10 ; j++ {
go func() {
req,err := httpDo(httpURL)
if err != nil {
log.Println("http request error :",err.Error())
}else {
log.Println("http request success:",string(req))
}
}()
}
time.Sleep(time.Second*5)
}
}
//http请求
func httpDo(url string) (respBytes []byte, err error) {
var resp *http.Response
err = hystrix.Do("svc1",func() error {
resp,err = http.Get(url)
if err != nil {
return err
}
respBytes,err = ioutil.ReadAll(resp.Body)
if err !=nil {
return err
}
return nil
}, func(error) error {
return errors.New("http request error")
})
return
}
go run client.go

可以看到断路器在这10次请求中反复被打开
思考:
1.可以将MaxConcurrentRequests改成7,观察断路器是否会被打开,
2. 将MaxConcurrentRequests的值改为10,在client运行过程中关闭svc,过一会儿再打开svc,观察情况
1万+



被折叠的 条评论
为什么被折叠?



