From 298ae270ebcd838c2f660d81c2d5cea5075e8d90 Mon Sep 17 00:00:00 2001 From: Edward Date: Fri, 15 May 2020 18:31:56 +0800 Subject: [PATCH] [WIP] RequestBreaker --- resiliency/06_circuit_breaker/README.md | 1 + resiliency/06_circuit_breaker/circuit_breaker.go | 14 ++++++++------ .../06_circuit_breaker/circuit_breaker_test.go | 2 +- 3 files changed, 10 insertions(+), 7 deletions(-) diff --git a/resiliency/06_circuit_breaker/README.md b/resiliency/06_circuit_breaker/README.md index dd4fcd7..cb80807 100644 --- a/resiliency/06_circuit_breaker/README.md +++ b/resiliency/06_circuit_breaker/README.md @@ -27,5 +27,6 @@ Circuit Breaker Pattern 也叫断路器模式,断路器设计模式是故障 上下文用于传递参数. 参考: + diff --git a/resiliency/06_circuit_breaker/circuit_breaker.go b/resiliency/06_circuit_breaker/circuit_breaker.go index 476ea03..3d08f8e 100644 --- a/resiliency/06_circuit_breaker/circuit_breaker.go +++ b/resiliency/06_circuit_breaker/circuit_breaker.go @@ -70,13 +70,13 @@ func NewRequestBreaker(opts ...Option) *RequestBreaker { } } -// Do runs the given request if the RequestBreaker accepts it. +// Do the given requested work if the RequestBreaker accepts it. // 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(req func() (interface{}, error)) (interface{}, error) { - - result, err := req() +func (rb *RequestBreaker) Do(work func() (interface{}, error)) (interface{}, error) { + //do work from requested user + result, err := work() return result, err } @@ -119,6 +119,7 @@ func (c *counters) Reset() { } +//Count the failure and success func (c *counters) Count(statue State) { switch statue { @@ -132,9 +133,10 @@ func (c *counters) Count(statue State) { } -//Breaker of circuit -func Breaker(c Circuit, failureThreshold uint32) Circuit { +//WrapperBreaker return a Wrapper to hold request +func WrapperBreaker(c Circuit, failureThreshold uint32) Circuit { + //内部计数器 cnt := counters{} return func(ctx context.Context) error { diff --git a/resiliency/06_circuit_breaker/circuit_breaker_test.go b/resiliency/06_circuit_breaker/circuit_breaker_test.go index c002a9a..8e08289 100644 --- a/resiliency/06_circuit_breaker/circuit_breaker_test.go +++ b/resiliency/06_circuit_breaker/circuit_breaker_test.go @@ -37,7 +37,7 @@ func TestBasicBreaker(t *testing.T) { // Get wraps http.Get in CircuitBreaker. func Get(url string) ([]byte, error) { - body, err := breaker.Execute(func() (interface{}, error) { + body, err := breaker.Do(func() (interface{}, error) { resp, err := http.Get(url) if err != nil { return nil, err