Example
Evan Huus
9 years ago
0 | 0 |
circuit-breaker
|
1 | 1 |
===============
|
2 | 2 |
|
3 | |
The circuit-breaker resiliency pattern for golang
|
|
3 |
The circuit-breaker resiliency pattern for golang.
|
|
4 |
|
|
5 |
Creating a breaker takes three parameters:
|
|
6 |
- error threshold (for opening the breaker)
|
|
7 |
- success threshold (for closing the breaker)
|
|
8 |
- timeout (how long to keep the breaker open)
|
|
9 |
|
|
10 |
```golang
|
|
11 |
breaker := breaker.New(3, 1, 5*time.Second)
|
|
12 |
|
|
13 |
for {
|
|
14 |
result := breaker.Run(func() error {
|
|
15 |
// communicate with some external service and
|
|
16 |
// return an error if the communication failed
|
|
17 |
return nil
|
|
18 |
})
|
|
19 |
|
|
20 |
switch result {
|
|
21 |
case nil:
|
|
22 |
// success!
|
|
23 |
case BreakerOpen:
|
|
24 |
// our function wasn't run because the breaker was open
|
|
25 |
default:
|
|
26 |
// some other error
|
|
27 |
}
|
|
28 |
}
|
|
29 |
```
|
75 | 75 |
t.Error(err)
|
76 | 76 |
}
|
77 | 77 |
}
|
|
78 |
|
|
79 |
func ExampleBreaker() {
|
|
80 |
breaker := New(3, 1, 5*time.Second)
|
|
81 |
|
|
82 |
for {
|
|
83 |
result := breaker.Run(func() error {
|
|
84 |
// communicate with some external service and
|
|
85 |
// return an error if the communication failed
|
|
86 |
return nil
|
|
87 |
})
|
|
88 |
|
|
89 |
switch result {
|
|
90 |
case nil:
|
|
91 |
// success!
|
|
92 |
case BreakerOpen:
|
|
93 |
// our function wasn't run because the breaker was open
|
|
94 |
default:
|
|
95 |
// some other error
|
|
96 |
}
|
|
97 |
}
|
|
98 |
}
|