fix error and make up codes for circuit breakers patters

This commit is contained in:
Edward 2020-04-29 22:29:00 +08:00
parent 51a141a35e
commit 278efd1524
3 changed files with 45 additions and 13 deletions

View File

@ -56,7 +56,8 @@ Go常用的、面向工程化和最佳实践的模式套路包含常见的23
[菜鸟教程—设计模式](https://www.runoob.com/design-pattern/design-pattern-tutorial.html)
[GO设计模式](https://github.com/senghoo/golang-design-pattern)
[23-Pattern-in-Go](https://github.com/senghoo/golang-design-pattern)
## 更多

View File

@ -1,16 +1,14 @@
package profile
package timeprofile
import (
"log"
"math/big"
"time"
"testing"
"time"
)
func TestBigintProfile(t *testing.T) {
bigint := big.NewInt(14468)
BigIntFactorial(bigint)
@ -21,7 +19,6 @@ func TestBigintProfile(t *testing.T) {
}
//Duration for time differ
func Duration(invocation time.Time, name string) {
elapsed := time.Since(invocation)

View File

@ -2,9 +2,14 @@ package circuit
import (
"context"
"errors"
"time"
)
var (
ErrServiceUnavailable = errors.New("Service Unavailable")
)
type State int
const (
@ -13,6 +18,7 @@ const (
SuccessState
)
//Counter interface
type Counter interface {
Count(State)
ConsecutiveFailures() uint32
@ -20,19 +26,47 @@ type Counter interface {
Reset()
}
type counters struct {
state State
lastActivity time.Time
}
func (c *counters) Count(State) {
}
func (c *counters) ConsecutiveFailures() uint32 {
return 0
}
func (c *counters) LastActivity() time.Time {
return c.lastActivity
}
func (c *counters) Reset() {
}
func NewCounter() Counter {
var i Counter
return i
}
type Circuit func(context.Context) error
func Breaker(c Circuit, failureThreshold uint32) Circuit {
cnt := NewCounter()
return func(ctx context) error {
return func(ctx context.Context) error {
if cnt.ConsecutiveFailures() >= failureThreshold {
canRetry := func(cnt Counter) {
backoffLevel := Cnt.ConsecutiveFailures() - failureThreshold
canRetry := func(cnt Counter) bool {
backoffLevel := cnt.ConsecutiveFailures() - failureThreshold
// Calculates when should the circuit breaker resume propagating requests
// to the service
shouldRetryAt := cnt.LastActivity().Add(time.Seconds * 2 << backoffLevel)
shouldRetryAt := cnt.LastActivity().Add(time.Second * 2 << backoffLevel)
return time.Now().After(shouldRetryAt)
}