go-pattern-examples/resiliency/06_circuit_breaker/circuit_counter.go

80 lines
1.6 KiB
Go
Raw Normal View History

2020-05-22 08:21:54 +03:00
/*
* @Description: https://github.com/crazybber
* @Author: Edward
* @Date: 2020-05-22 12:41:54
* @Last Modified by: Edward
2020-05-22 12:57:41 +03:00
* @Last Modified time: 2020-05-22 17:22:35
2020-05-22 08:21:54 +03:00
*/
package circuit
import "time"
2020-05-22 10:31:28 +03:00
////////////////////////////////
/// 计数器 用以维护断路器内部的状态
/// 无论是对象式断路器还是函数式断路器
/// 都要用到计数器
////////////////////////////////
//State 断路器本身的状态的
//State of switch int
type State int
2020-05-22 08:21:54 +03:00
2020-05-22 10:31:28 +03:00
// state for breaker
2020-05-22 08:21:54 +03:00
const (
2020-05-22 10:31:28 +03:00
StateClosed State = iota //默认的闭合状态,可以正常执行业务
StateHalfOpen
StateOpen
2020-06-02 18:55:42 +03:00
StateUnknown
2020-05-22 08:21:54 +03:00
)
2020-05-22 10:31:28 +03:00
//OperationState of current 某一次操作的结果状态
type OperationState int
2020-05-22 08:21:54 +03:00
//ICounter interface
type ICounter interface {
Count(OperationState)
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) {
switch statue {
case FailureState:
c.ConsecutiveFailures++
case SuccessState:
c.ConsecutiveSuccesses++
}
c.Requests++
c.lastActivity = time.Now() //更新活动时间
2020-05-22 12:57:41 +03:00
// c.lastOpResult = statue
2020-05-22 08:21:54 +03:00
//handle status change
}