[WIP] RequestBreaker

This commit is contained in:
Edward 2020-05-15 18:31:56 +08:00
parent 78ae8f6954
commit 298ae270eb
3 changed files with 10 additions and 7 deletions

View File

@ -27,5 +27,6 @@ Circuit Breaker Pattern 也叫断路器模式,断路器设计模式是故障
上下文用于传递参数.
参考:
<https://msdn.microsoft.com/en-us/library/dn589784.aspx>
<https://blog.csdn.net/jeffrey11223/article/details/85541923>

View File

@ -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 {

View File

@ -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