[WIP] circuit_breaker

This commit is contained in:
Edward 2020-05-11 22:00:45 +08:00
parent f0007a48e4
commit 2da17c4024
3 changed files with 12 additions and 12 deletions

View File

@ -12,8 +12,8 @@ type Options struct {
OnStateChanged StateChangedEventHandler
}
//SetName of breaker
func SetName(name string) Option {
//Name of breaker
func Name(name string) Option {
return func(opts *Options) {
opts.Name = name
}

View File

@ -5,7 +5,7 @@ package circuit
* @Author: Edward
* @Date: 2020-05-10 22:00:58
* @Last Modified by: Edward
* @Last Modified time: 2020-05-11 17:46:20
* @Last Modified time: 2020-05-11 21:37:13
*/
import (
@ -92,10 +92,11 @@ type ICounter interface {
}
type counters struct {
Requests uint32
state State
lastActivity time.Time
counts uint32 //counts of failures
TotalFailures, Requests uint32
state State
lastActivity time.Time
counts uint32 //counts of failures
}
func (c *counters) Count(state State) {
@ -129,6 +130,7 @@ func Breaker(c Circuit, failureThreshold uint32) Circuit {
if cnt.ConsecutiveFailures() >= failureThreshold {
canRetry := func(cnt ICounter) bool {
backoffLevel := cnt.ConsecutiveFailures() - failureThreshold
// Calculates when should the circuit breaker resume propagating requests

View File

@ -3,7 +3,7 @@
* @Author: Edward
* @Date: 2020-05-11 10:55:28
* @Last Modified by: Edward
* @Last Modified time: 2020-05-11 10:55:28
* @Last Modified time: 2020-05-11 21:35:39
*/
package circuit
@ -19,15 +19,13 @@ var breaker *RequestBreaker
func TestBasicBreaker(t *testing.T) {
var st Options
st.Name = "HTTP GET"
st.ReadyToTrip = func(counts counters) bool {
readyToTrip := func(counts counters) bool {
//失败率,可以由用户自己定义
failureRatio := float64(counts.TotalFailures) / float64(counts.Requests)
return counts.Requests >= 3 && failureRatio >= 0.6
}
breaker = NewRequestBreaker(st)
breaker = NewRequestBreaker(Name("HTTP GET"), ReadyToTrip(readyToTrip))
body, err := Get("https://bing.com/robots.txt")
if err != nil {