mirror of
https://github.com/crazybber/go-pattern-examples.git
synced 2024-11-22 03:46:03 +03:00
add a context for params
This commit is contained in:
parent
48a219b987
commit
7b0110f123
@ -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
|
||||
|
@ -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())
|
||||
|
||||
|
@ -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
|
||||
|
Loading…
Reference in New Issue
Block a user