[WIP] circuit_breaker

This commit is contained in:
Edward 2020-05-11 14:31:25 +08:00
parent de05ba5cc9
commit 679e87c4cb
4 changed files with 45 additions and 9 deletions

View File

@ -4,13 +4,12 @@ import "time"
//Options for breaker //Options for breaker
type Options struct { type Options struct {
Name string Name string
Expiry time.Time Expiry time.Time
Interval time.Duration Interval, Timeout time.Duration
Timeout time.Duration MaxRequests uint32
MaxRequests uint32 ReadyToTrip StateCheckerHandler
ReadyToTrip StateCheckerHandler OnStateChanged StateChangedEventHandler
OnStateChanged StateChangedEventHandler
} }
//SetName of breaker //SetName of breaker

View File

@ -5,7 +5,7 @@ package circuit
* @Author: Edward * @Author: Edward
* @Date: 2020-05-10 22:00:58 * @Date: 2020-05-10 22:00:58
* @Last Modified by: Edward * @Last Modified by: Edward
* @Last Modified time: 2020-05-10 22:02:18 * @Last Modified time: 2020-05-11 11:57:21
*/ */
import ( import (
@ -46,8 +46,28 @@ type RequestBreaker struct {
} }
//NewRequestBreaker return a breaker //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 //State of current switch

View File

@ -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 package circuit
import ( import (
@ -14,6 +22,7 @@ func TestBasicBreaker(t *testing.T) {
var st Options var st Options
st.Name = "HTTP GET" st.Name = "HTTP GET"
st.ReadyToTrip = func(counts counters) bool { st.ReadyToTrip = func(counts counters) bool {
//失败率,可以由用户自己定义
failureRatio := float64(counts.TotalFailures) / float64(counts.Requests) failureRatio := float64(counts.TotalFailures) / float64(counts.Requests)
return counts.Requests >= 3 && failureRatio >= 0.6 return counts.Requests >= 3 && failureRatio >= 0.6
} }

View File

@ -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 package parallelism
import ( import (