go-pattern-examples/resiliency/06_circuit_breaker/circuit_breaker_test.go

48 lines
967 B
Go
Raw Normal View History

2020-05-11 09:31:25 +03:00
/*
* @Description: https://github.com/crazybber
* @Author: Edward
* @Date: 2020-05-11 10:55:28
* @Last Modified by: Edward
2020-05-11 17:00:45 +03:00
* @Last Modified time: 2020-05-11 21:35:39
2020-05-11 09:31:25 +03:00
*/
2020-04-28 17:48:09 +03:00
package circuit
import (
2020-05-10 17:03:24 +03:00
"fmt"
"io/ioutil"
"net/http"
2020-05-08 10:51:33 +03:00
"testing"
2020-04-28 17:48:09 +03:00
)
2020-05-10 17:03:24 +03:00
var breaker *RequestBreaker
2020-05-08 10:51:33 +03:00
func TestBasicBreaker(t *testing.T) {
2020-04-28 17:48:09 +03:00
2020-05-11 17:00:45 +03:00
readyToTrip := func(counts counters) bool {
2020-05-11 09:31:25 +03:00
//失败率,可以由用户自己定义
2020-05-10 17:03:24 +03:00
failureRatio := float64(counts.TotalFailures) / float64(counts.Requests)
return counts.Requests >= 3 && failureRatio >= 0.6
}
2020-05-11 17:00:45 +03:00
breaker = NewRequestBreaker(Name("HTTP GET"), ReadyToTrip(readyToTrip))
2020-05-10 17:03:24 +03:00
2020-05-15 13:31:56 +03:00
body, err := breaker.Do(func() (interface{}, error) {
2020-05-19 12:56:40 +03:00
resp, err := http.Get("https://bing.com/robots.txt")
2020-05-10 17:03:24 +03:00
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 {
2020-05-19 12:56:40 +03:00
t.Fatal(err)
2020-05-10 17:03:24 +03:00
}
2020-05-19 12:56:40 +03:00
fmt.Println(string(body.([]byte)))
2020-04-28 17:48:09 +03:00
}