mirror of
https://github.com/crazybber/go-pattern-examples.git
synced 2024-11-21 19:36:03 +03:00
[WIP] circuit_breaker
This commit is contained in:
parent
de05ba5cc9
commit
679e87c4cb
@ -4,13 +4,12 @@ import "time"
|
||||
|
||||
//Options for breaker
|
||||
type Options struct {
|
||||
Name string
|
||||
Expiry time.Time
|
||||
Interval time.Duration
|
||||
Timeout time.Duration
|
||||
MaxRequests uint32
|
||||
ReadyToTrip StateCheckerHandler
|
||||
OnStateChanged StateChangedEventHandler
|
||||
Name string
|
||||
Expiry time.Time
|
||||
Interval, Timeout time.Duration
|
||||
MaxRequests uint32
|
||||
ReadyToTrip StateCheckerHandler
|
||||
OnStateChanged StateChangedEventHandler
|
||||
}
|
||||
|
||||
//SetName of breaker
|
||||
|
@ -5,7 +5,7 @@ package circuit
|
||||
* @Author: Edward
|
||||
* @Date: 2020-05-10 22:00:58
|
||||
* @Last Modified by: Edward
|
||||
* @Last Modified time: 2020-05-10 22:02:18
|
||||
* @Last Modified time: 2020-05-11 11:57:21
|
||||
*/
|
||||
|
||||
import (
|
||||
@ -46,8 +46,28 @@ type RequestBreaker struct {
|
||||
}
|
||||
|
||||
//NewRequestBreaker return a breaker
|
||||
func NewRequestBreaker() *RequestBreaker {
|
||||
func NewRequestBreaker(opts ...Option) *RequestBreaker {
|
||||
|
||||
defaultOptions := Options{
|
||||
Name: "defaultBreakerName",
|
||||
Expiry: time.Now().Add(time.Second * 20),
|
||||
Interval: time.Second * 2,
|
||||
Timeout: time.Second * 5,
|
||||
MaxRequests: 5,
|
||||
ReadyToTrip: func(counts counters) bool { return true },
|
||||
OnStateChanged: func(name string, from State, to State) {},
|
||||
}
|
||||
|
||||
for _, setOption := range opts {
|
||||
setOption(&defaultOptions)
|
||||
|
||||
}
|
||||
|
||||
return &RequestBreaker{
|
||||
options: defaultOptions,
|
||||
counts: nil,
|
||||
generation: 0,
|
||||
}
|
||||
}
|
||||
|
||||
//State of current switch
|
||||
|
@ -1,3 +1,11 @@
|
||||
/*
|
||||
* @Description: https://github.com/crazybber
|
||||
* @Author: Edward
|
||||
* @Date: 2020-05-11 10:55:28
|
||||
* @Last Modified by: Edward
|
||||
* @Last Modified time: 2020-05-11 10:55:28
|
||||
*/
|
||||
|
||||
package circuit
|
||||
|
||||
import (
|
||||
@ -14,6 +22,7 @@ func TestBasicBreaker(t *testing.T) {
|
||||
var st Options
|
||||
st.Name = "HTTP GET"
|
||||
st.ReadyToTrip = func(counts counters) bool {
|
||||
//失败率,可以由用户自己定义
|
||||
failureRatio := float64(counts.TotalFailures) / float64(counts.Requests)
|
||||
return counts.Requests >= 3 && failureRatio >= 0.6
|
||||
}
|
||||
|
@ -1,3 +1,11 @@
|
||||
/*
|
||||
* @Description: https://github.com/crazybber
|
||||
* @Author: Edward
|
||||
* @Date: 2020-05-11 10:44:52
|
||||
* @Last Modified by: Edward
|
||||
* @Last Modified time: 2020-05-11 10:44:52
|
||||
*/
|
||||
|
||||
package parallelism
|
||||
|
||||
import (
|
||||
|
Loading…
Reference in New Issue
Block a user