104 lines
2.5 KiB
Go
Raw Normal View History

/*
* @Description: https://github.com/crazybber
* @Author: Edward
* @Date: 2020-06-02 23:57:40
* @Last Modified by: Edward
2020-06-03 23:55:51 +08:00
* @Last Modified time: 2020-06-03 23:50:17
*/
2020-05-10 22:03:24 +08:00
package circuit
2020-05-22 18:14:19 +08:00
import (
"context"
"time"
)
2020-05-10 22:03:24 +08:00
2020-05-21 16:02:28 +08:00
//BreakConditionWatcher check state
2020-06-04 17:04:53 +08:00
type BreakConditionWatcher func(state State, cnter counters) bool
2020-05-21 16:02:28 +08:00
//StateChangedEventHandler set event handle
type StateChangedEventHandler func(name string, from State, to State)
//Option set Options
type Option func(opts *Options)
2020-05-10 22:03:24 +08:00
//Options for breaker
type Options struct {
2020-06-04 17:04:53 +08:00
Name string
Expiry time.Time
Interval, Timeout time.Duration
MaxRequests uint32
CanOpen BreakConditionWatcher //是否应该断开电路(打开电路开关)
CanClose BreakConditionWatcher //if we should close switch
OnStateChanged StateChangedEventHandler
ShoulderHalfToOpen uint32
Ctx context.Context
2020-05-10 22:03:24 +08:00
}
2020-06-04 17:04:53 +08:00
//ActionName of breaker
func ActionName(name string) Option {
2020-05-10 22:03:24 +08:00
return func(opts *Options) {
opts.Name = name
}
}
2020-05-11 18:01:25 +08:00
//Interval of breaker
func Interval(interval time.Duration) Option {
return func(opts *Options) {
opts.Interval = interval
}
}
//Timeout of breaker
func Timeout(timeout time.Duration) Option {
return func(opts *Options) {
opts.Timeout = timeout
}
}
// MaxRequests is the maximum number of requests allowed to pass through
// when the CircuitBreaker is half-open.
// If MaxRequests is 0, the CircuitBreaker allows only 1 request.
//MaxRequests of breaker
func MaxRequests(maxRequests uint32) Option {
return func(opts *Options) {
opts.MaxRequests = maxRequests
}
}
2020-06-04 17:04:53 +08:00
//WithShoulderHalfToOpen of breaker
func WithShoulderHalfToOpen(shoulderHalfToOpen uint32) Option {
return func(opts *Options) {
opts.ShoulderHalfToOpen = shoulderHalfToOpen
}
}
2020-05-11 18:01:25 +08:00
//Expiry of breaker
func Expiry(expiry time.Time) Option {
2020-05-10 22:03:24 +08:00
return func(opts *Options) {
opts.Expiry = expiry
}
}
2020-05-22 17:57:41 +08:00
//WithStateChanged set handle of ChangedHandle
func WithStateChanged(handler StateChangedEventHandler) Option {
2020-05-10 22:03:24 +08:00
return func(opts *Options) {
opts.OnStateChanged = handler
}
}
2020-06-04 17:04:53 +08:00
//WithBreakCondition check traffic state ,to see if request can go
func WithBreakCondition(whenCondition BreakConditionWatcher) Option {
return func(opts *Options) {
opts.CanOpen = whenCondition
}
}
//WithCloseCondition check traffic state ,to see if request can go
func WithCloseCondition(whenCondition BreakConditionWatcher) Option {
2020-05-10 22:03:24 +08:00
return func(opts *Options) {
2020-06-04 17:04:53 +08:00
opts.CanClose = whenCondition
2020-05-10 22:03:24 +08:00
}
}