From 2da17c4024bb7b175928e59250dc90a07b3b3653 Mon Sep 17 00:00:00 2001 From: Edward Date: Mon, 11 May 2020 22:00:45 +0800 Subject: [PATCH] [WIP] circuit_breaker --- resiliency/06_circuit_breaker/breaker_options.go | 4 ++-- resiliency/06_circuit_breaker/circuit_breaker.go | 12 +++++++----- .../06_circuit_breaker/circuit_breaker_test.go | 8 +++----- 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/resiliency/06_circuit_breaker/breaker_options.go b/resiliency/06_circuit_breaker/breaker_options.go index 6c4b0ac..5bd1497 100644 --- a/resiliency/06_circuit_breaker/breaker_options.go +++ b/resiliency/06_circuit_breaker/breaker_options.go @@ -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 } diff --git a/resiliency/06_circuit_breaker/circuit_breaker.go b/resiliency/06_circuit_breaker/circuit_breaker.go index bd5141d..7a3ab68 100644 --- a/resiliency/06_circuit_breaker/circuit_breaker.go +++ b/resiliency/06_circuit_breaker/circuit_breaker.go @@ -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 diff --git a/resiliency/06_circuit_breaker/circuit_breaker_test.go b/resiliency/06_circuit_breaker/circuit_breaker_test.go index 0fede6c..c002a9a 100644 --- a/resiliency/06_circuit_breaker/circuit_breaker_test.go +++ b/resiliency/06_circuit_breaker/circuit_breaker_test.go @@ -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 {