61 lines
1.1 KiB
Go
Raw Normal View History

2020-05-11 14:31:25 +08:00
/*
* @Description: https://github.com/crazybber
* @Author: Edward
* @Date: 2020-05-11 10:55:28
* @Last Modified by: Edward
* @Last Modified time: 2020-05-11 10:55:28
*/
2020-04-28 22:48:09 +08:00
package circuit
import (
2020-05-10 22:03:24 +08:00
"fmt"
"io/ioutil"
"net/http"
2020-05-08 15:51:33 +08:00
"testing"
2020-04-28 22:48:09 +08:00
)
2020-05-10 22:03:24 +08:00
var breaker *RequestBreaker
2020-05-08 15:51:33 +08:00
func TestBasicBreaker(t *testing.T) {
2020-04-28 22:48:09 +08:00
2020-05-10 22:03:24 +08:00
var st Options
st.Name = "HTTP GET"
st.ReadyToTrip = func(counts counters) bool {
2020-05-11 14:31:25 +08:00
//失败率,可以由用户自己定义
2020-05-10 22:03:24 +08:00
failureRatio := float64(counts.TotalFailures) / float64(counts.Requests)
return counts.Requests >= 3 && failureRatio >= 0.6
}
breaker = NewRequestBreaker(st)
body, err := Get("https://bing.com/robots.txt")
if err != nil {
t.Fatal(err)
}
fmt.Println(string(body))
}
// Get wraps http.Get in CircuitBreaker.
func Get(url string) ([]byte, error) {
body, err := breaker.Execute(func() (interface{}, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return body, nil
})
if err != nil {
return nil, err
}
return body.([]byte), nil
2020-04-28 22:48:09 +08:00
}