-
Notifications
You must be signed in to change notification settings - Fork 23
/
circuit_breaker_test.go
105 lines (84 loc) · 2.2 KB
/
circuit_breaker_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/*
* @Description: https://github.com/crazybber
* @Author: Edward
* @Date: 2020-05-11 10:55:28
* @Last Modified by: Edward
* @Last Modified time: 2020-05-22 17:21:06
*/
package circuit
import (
"context"
"fmt"
"io/ioutil"
"log"
"net/http"
"testing"
)
var breaker *RequestBreaker
var onStateChangeEvent = func(name string, from, to State) {
fmt.Println("name:", name, "from:", from, "to", to)
}
var canOpenSwitch = func(current State, cnter counters) bool {
if current == StateHalfOpen {
return cnter.ConsecutiveFailures > 2
}
//失败率,可以由用户自己定义
failureRatio := float64(cnter.TotalFailures) / float64(cnter.Requests)
return cnter.Requests >= 3 && failureRatio >= 0.6
}
var canCloseSwitch = func(current State, cnter counters) bool {
//失败率,可以由用户自己定义
if cnter.ConsecutiveSuccesses > 2 {
return true
}
//
successRatio := float64(cnter.TotalFailures) / float64(cnter.Requests)
return cnter.Requests >= 3 && successRatio >= 0.6
}
func TestObjectBreaker(t *testing.T) {
jobToDo := func(ctx context.Context) (interface{}, error) {
resp, err := http.Get("https://bing.com/robots.txt")
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
}
breaker = NewRequestBreaker(ActionName("HTTP GET"),
WithBreakCondition(canOpenSwitch),
WithCloseCondition(canCloseSwitch),
WithShoulderHalfToOpen(2),
WithStateChanged(onStateChangeEvent))
body, err := breaker.Do(jobToDo)
if err != nil {
t.Fatal(err)
}
fmt.Println(string(body.([]byte)))
log.Print("\nresult:", body.([]byte))
}
func TestFunctionalBreaker(t *testing.T) {
//something need to do
jobToDo := func(ctx context.Context) error {
resp, err := http.Get("https://bing.com/robots.txt")
if err != nil {
return err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
fmt.Println(string(body))
return nil
}
//wrapper and control job with a breaker
circuitWork := Breaker(jobToDo, 2 /* failureThreshold */)
params := context.TODO()
// do the job as usually
res := circuitWork(params)
log.Print("\nresult:", res)
}