| 1 |
circuit-breaker |
| 2 |
=============== |
| 3 |
|
| 4 |
[](https://github.com/eapache/go-resiliency/actions/workflows/golang-ci.yml) |
| 5 |
[](https://godoc.org/github.com/eapache/go-resiliency/breaker) |
| 6 |
[](https://eapache.github.io/conduct.html) |
| 7 |
|
| 8 |
The circuit-breaker resiliency pattern for golang. |
| 9 |
|
| 10 |
Creating a breaker takes three parameters: |
| 11 |
- error threshold (for opening the breaker) |
| 12 |
- success threshold (for closing the breaker) |
| 13 |
- timeout (how long to keep the breaker open) |
| 14 |
|
| 15 |
```go |
| 16 |
b := breaker.New(3, 1, 5*time.Second) |
| 17 |
|
| 18 |
for { |
| 19 |
result := b.Run(func() error { |
| 20 |
// communicate with some external service and |
| 21 |
// return an error if the communication failed |
| 22 |
return nil |
| 23 |
}) |
| 24 |
|
| 25 |
switch result { |
| 26 |
case nil: |
| 27 |
// success! |
| 28 |
case breaker.ErrBreakerOpen: |
| 29 |
// our function wasn't run because the breaker was open |
| 30 |
default: |
| 31 |
// some other error |
| 32 |
} |
| 33 |
} |
| 34 |
``` |