Skip to content

Commit d156b7d

Browse files
committed
use single field instead of two fields
1 parent 5465428 commit d156b7d

File tree

1 file changed

+6
-16
lines changed

1 file changed

+6
-16
lines changed

โ€Žclient/circuit_breaker.goโ€Ž

Lines changed: 6 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,7 @@ var (
1313

1414
// ConsecCircuitBreaker is window sliding CircuitBreaker with failure threshold.
1515
type 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

6967
func (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 {
8078
func (cb *ConsecCircuitBreaker) success() {
8179
cb.reset()
8280
}
81+
8382
func (cb *ConsecCircuitBreaker) fail() {
8483
atomic.AddUint64(&cb.failures, 1)
85-
cb.updateLastFailureTime(time.Now())
84+
atomic.StoreInt64(&cb.lastFailureTime, time.Now().UnixNano())
8685
}
8786

8887
func (cb *ConsecCircuitBreaker) Success() {
8988
cb.success()
9089
}
90+
9191
func (cb *ConsecCircuitBreaker) Fail() {
9292
cb.fail()
9393
}
@@ -98,15 +98,5 @@ func (cb *ConsecCircuitBreaker) Ready() bool {
9898

9999
func (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

Comments
ย (0)