From 7b0110f12366e3bd7b77ca9e33f4c37a4400ce50 Mon Sep 17 00:00:00 2001 From: Edward Date: Fri, 22 May 2020 18:14:19 +0800 Subject: [PATCH] add a context for params --- .../06_circuit_breaker/breaker_options.go | 6 +++++- .../06_circuit_breaker/circuit_breaker.go | 21 +++++++++++++------ .../circuit_breaker_test.go | 2 +- 3 files changed, 21 insertions(+), 8 deletions(-) diff --git a/resiliency/06_circuit_breaker/breaker_options.go b/resiliency/06_circuit_breaker/breaker_options.go index f139ad4..d5ef032 100644 --- a/resiliency/06_circuit_breaker/breaker_options.go +++ b/resiliency/06_circuit_breaker/breaker_options.go @@ -1,6 +1,9 @@ package circuit -import "time" +import ( + "context" + "time" +) //BreakConditionWatcher check state type BreakConditionWatcher func(cnter counters) bool @@ -19,6 +22,7 @@ type Options struct { MaxRequests uint32 WhenToBreak BreakConditionWatcher //是否应该断开电路(打开电路开关) OnStateChanged StateChangedEventHandler + Ctx context.Context } //Name of breaker diff --git a/resiliency/06_circuit_breaker/circuit_breaker.go b/resiliency/06_circuit_breaker/circuit_breaker.go index fc4e15d..47a6395 100644 --- a/resiliency/06_circuit_breaker/circuit_breaker.go +++ b/resiliency/06_circuit_breaker/circuit_breaker.go @@ -9,10 +9,12 @@ package circuit import ( - "errors" + "context" + "context + "erros" "fmt" "sync" - "time" + time" ) //////////////////////////////// @@ -77,19 +79,26 @@ func NewRequestBreaker(opts ...Option) *RequestBreaker { // Do returns an error instantly if the RequestBreaker rejects the request. // Otherwise, Execute returns the result of the request. // If a panic occurs in the request, the RequestBreaker handles it as an error and causes the same panic again. -func (rb *RequestBreaker) Do(work func() (interface{}, error)) (interface{}, error) { +func (rb *RequestBreaker) Do(work func(ctx context.Context) (interface{}, error)) (interface{}, error) { //before fmt.Println("before do : request:", rb.cnter.Total()) - //handle status - + rb.mutex.Lock() + //handle status of Open to HalfOpen if rb.state == StateOpen && rb.options.Expiry.Before(time.Now()) { } + rb.mutex.Unlock() //do work from requested user - result, err := work() + result, err := work(rb.options.Ctx) + + if err != nil { + rb.cnter.Count(FailureState) + } else { + rb.cnter.Count(SuccessState) + } fmt.Println("after do : request:", rb.cnter.Total()) diff --git a/resiliency/06_circuit_breaker/circuit_breaker_test.go b/resiliency/06_circuit_breaker/circuit_breaker_test.go index 5e9a596..a2bf61e 100644 --- a/resiliency/06_circuit_breaker/circuit_breaker_test.go +++ b/resiliency/06_circuit_breaker/circuit_breaker_test.go @@ -31,7 +31,7 @@ var whenConditionOccurred = func(cnter counters) bool { func TestObjectBreaker(t *testing.T) { - jobToDo := func() (interface{}, error) { + jobToDo := func(ctx context.Context) (interface{}, error) { resp, err := http.Get("https://bing.com/robots.txt") if err != nil { return nil, err