1313
1414// ConsecCircuitBreaker is window sliding CircuitBreaker with failure threshold.
1515type ConsecCircuitBreaker struct {
16- // time.Time is a compund type, split into second and nano for using atomic.
17- lastFailureTimeSecond int64
18- lastFailureTimeNano int32
16+ lastFailureTime int64
1917
2018 failures uint64
2119 failureThreshold uint64
@@ -67,7 +65,7 @@ func (cb *ConsecCircuitBreaker) Call(fn func() error, d time.Duration) error {
6765}
6866
6967func (cb * ConsecCircuitBreaker ) ready () bool {
70- lastFailureTime := cb . loadLastFailureTime ( )
68+ lastFailureTime := time . Unix ( 0 , atomic . LoadInt64 ( & cb . lastFailureTime ) )
7169 if time .Since (lastFailureTime ) > cb .window {
7270 cb .reset ()
7371 return true
@@ -80,14 +78,16 @@ func (cb *ConsecCircuitBreaker) ready() bool {
8078func (cb * ConsecCircuitBreaker ) success () {
8179 cb .reset ()
8280}
81+
8382func (cb * ConsecCircuitBreaker ) fail () {
8483 atomic .AddUint64 (& cb .failures , 1 )
85- cb . updateLastFailureTime ( time .Now ())
84+ atomic . StoreInt64 ( & cb . lastFailureTime , time .Now (). UnixNano ())
8685}
8786
8887func (cb * ConsecCircuitBreaker ) Success () {
8988 cb .success ()
9089}
90+
9191func (cb * ConsecCircuitBreaker ) Fail () {
9292 cb .fail ()
9393}
@@ -98,15 +98,5 @@ func (cb *ConsecCircuitBreaker) Ready() bool {
9898
9999func (cb * ConsecCircuitBreaker ) reset () {
100100 atomic .StoreUint64 (& cb .failures , 0 )
101- cb .updateLastFailureTime (time .Now ())
102- }
103-
104- func (cb * ConsecCircuitBreaker ) updateLastFailureTime (cur time.Time ) {
105- atomic .StoreInt64 (& cb .lastFailureTimeSecond , cur .Unix ())
106- atomic .StoreInt32 (& cb .lastFailureTimeNano , int32 (cur .UnixNano ()))
107- }
108- func (cb * ConsecCircuitBreaker ) loadLastFailureTime () time.Time {
109- nano := atomic .LoadInt32 (& cb .lastFailureTimeNano )
110- second := atomic .LoadInt64 (& cb .lastFailureTimeSecond )
111- return time .Unix (second , int64 (nano ))
101+ atomic .StoreInt64 (& cb .lastFailureTime , time .Now ().UnixNano ())
112102}
0 commit comments