-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathcircuit_counter.go
85 lines (71 loc) · 1.74 KB
/
circuit_counter.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*
* @Description: https://github.com/crazybber
* @Author: Edward
* @Date: 2020-05-22 12:41:54
* @Last Modified by: Edward
* @Last Modified time: 2020-05-22 17:22:35
*/
package circuit
import "time"
////////////////////////////////
/// 计数器 用以维护断路器内部的状态
/// 无论是对象式断路器还是函数式断路器
/// 都要用到计数器
////////////////////////////////
//State 断路器本身的状态的
//State of switch int
type State int
// state for breaker
const (
StateClosed State = iota //默认的闭合状态,可以正常执行业务
StateHalfOpen
StateOpen
StateUnknown
)
//OperationState of current 某一次操作的结果状态
type OperationState int
//ICounter interface
type ICounter interface {
Count(OperationState, bool)
LastActivity() time.Time
Reset()
Total() uint32
}
type counters struct {
Requests uint32 //连续的请求次数
lastActivity time.Time
TotalFailures uint32
TotalSuccesses uint32
ConsecutiveSuccesses uint32
ConsecutiveFailures uint32
}
func (c *counters) Total() uint32 {
return c.Requests
}
func (c *counters) LastActivity() time.Time {
return c.lastActivity
}
func (c *counters) Reset() {
ct := &counters{}
ct.lastActivity = c.lastActivity
c = ct
}
//Count the failure and success
func (c *counters) Count(statue OperationState, isConsecutive bool) {
switch statue {
case FailureState:
c.TotalFailures++
if isConsecutive || c.ConsecutiveFailures == 0 {
c.ConsecutiveFailures++
}
case SuccessState:
c.TotalSuccesses++
if isConsecutive || c.ConsecutiveSuccesses == 0 {
c.ConsecutiveSuccesses++
}
}
c.Requests++
c.lastActivity = time.Now() //更新活动时间
// c.lastOpResult = statue
//handle status change
}