update breaker patterns

This commit is contained in:
Edward 2020-05-08 19:34:48 +08:00
parent 04f7a40113
commit f60c5af803
3 changed files with 34 additions and 31 deletions

View File

@ -21,11 +21,10 @@ const (
type Breaker struct {
errorThreshold, successThreshold int
timeout time.Duration
lock sync.Mutex
state uint32
errors, successes int
lastError time.Time
lock sync.Mutex
state uint32
errors, successes int
lastError time.Time
}
// New constructs a new circuit-breaker that starts closed.

View File

@ -20,6 +20,27 @@ func returnsSuccess() error {
return nil
}
func TestExampleBreaker(t *testing.T) {
breaker := New(3, 1, 5*time.Second)
for {
result := breaker.Run(func() error {
// communicate with some external service and
// return an error if the communication failed
return nil
})
switch result {
case nil:
// success!
case ErrBreakerOpen:
// our function wasn't run because the breaker was open
default:
// some other error
}
}
}
func TestBreakerErrorExpiry(t *testing.T) {
breaker := New(2, 1, 1*time.Second)
@ -173,24 +194,3 @@ func TestBreakerAsyncStateTransitions(t *testing.T) {
t.Error(err)
}
}
func ExampleBreaker() {
breaker := New(3, 1, 5*time.Second)
for {
result := breaker.Run(func() error {
// communicate with some external service and
// return an error if the communication failed
return nil
})
switch result {
case nil:
// success!
case ErrBreakerOpen:
// our function wasn't run because the breaker was open
default:
// some other error
}
}
}

View File

@ -8,13 +8,17 @@ import (
//ErrServiceUnavailable for error
var (
ErrServiceUnavailable = errors.New("Service Unavailable")
ErrTooManyRequests = errors.New("too many requests")
ErrServiceUnavailable = errors.New("service unavailable")
FailureThreshold = 10
)
//State of current switch
type State int
//states of CircuitBreaker
const (
UnknownState uint = iota
UnknownState State = iota
FailureState
SuccessState
)
@ -24,19 +28,19 @@ type Circuit func(context.Context) error
//Counter interface
type Counter interface {
Count(uint)
Count(State)
ConsecutiveFailures() uint32
LastActivity() time.Time
Reset()
}
type counters struct {
state uint
state State
lastActivity time.Time
counts uint32 //counts of failures
}
func (c *counters) Count(state uint) {
func (c *counters) Count(state State) {
}