add a state check

This commit is contained in:
Edward 2020-05-22 18:39:31 +08:00
parent 7b0110f123
commit c3699e7c11
3 changed files with 23 additions and 5 deletions

View File

@ -20,7 +20,7 @@ Circuit Breaker Pattern 也叫断路器模式,断路器设计模式是故障
## Circuit Breaker 断路器
如果电路连续故障超过指定的阈值,它将返回一个快速错误,一段时间后,它会重试请求并记录它
电路连续故障,并且超过指定的阈值,它将返回一个快速错误,一段时间后,才会重试请求
## Context

View File

@ -10,11 +10,10 @@ package circuit
import (
"context"
"context
"erros"
"errors"
"fmt"
"sync"
time"
"time"
)
////////////////////////////////
@ -87,10 +86,29 @@ func (rb *RequestBreaker) Do(work func(ctx context.Context) (interface{}, error)
rb.mutex.Lock()
//handle status of Open to HalfOpen
if rb.state == StateOpen && rb.options.Expiry.Before(time.Now()) {
rb.state = StateHalfOpen
rb.cnter.Reset()
rb.options.OnStateChanged(rb.options.Name, StateOpen, StateHalfOpen)
}
rb.mutex.Unlock()
switch rb.state {
case StateOpen:
return nil, ErrTooManyRequests
case StateHalfOpen:
//do work from requested user
result, err := work(rb.options.Ctx)
if err != nil {
rb.cnter.Count(FailureState)
} else {
rb.cnter.Count(SuccessState)
return result, nil
}
case StateClosed:
}
//do work from requested user
result, err := work(rb.options.Ctx)