mirror of
https://github.com/crazybber/go-pattern-examples.git
synced 2024-11-22 03:46:03 +03:00
add a state check
This commit is contained in:
parent
7b0110f123
commit
c3699e7c11
@ -20,7 +20,7 @@ Circuit Breaker Pattern 也叫断路器模式,断路器设计模式是故障
|
||||
|
||||
## Circuit Breaker 断路器
|
||||
|
||||
如果电路连续故障超过指定的阈值,它将返回一个快速错误,一段时间后,它会重试请求并记录它。
|
||||
电路连续故障,并且超过指定的阈值,它将返回一个快速错误,一段时间后,才会重试请求。
|
||||
|
||||
## Context
|
||||
|
||||
|
@ -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)
|
||||
|
Loading…
Reference in New Issue
Block a user