Circuit Breaker

Circuit breaker middleware for providing client-side breaker functionality, with sre breaker algorithm implemented by default。

Configuration

WithGroup

breaker depends on container/group to implement the use of mutually independent breaker for different Operation. use WithGroup to configure a costom Breaker to replace the default breaker algorithm:

  1. // WithGroup with circuit breaker group.
  2. // NOTE: implements generics circuitbreaker.CircuitBreaker
  3. func WithGroup(g *group.Group) Option {
  4. return func(o *options) {
  5. o.group = g
  6. }
  7. }

The default configuration generates separate breakers for different Operation(s).

  1. opt := &options{
  2. group: group.NewGroup(func() interface{} {
  3. return sre.NewBreaker()
  4. }),
  5. }

group.Group is a lazy load container . The instance of group.Group should be implement the CircuitBreaker interface in aegis/circuitbreaker

  1. // CircuitBreaker is a circuit breaker.
  2. type CircuitBreaker interface {
  3. Allow() error // it means rejected when return error
  4. MarkSuccess()
  5. MarkFailed()
  6. }

Usage

Use circuit breaker in client

  1. // http
  2. conn, err := http.NewClient(
  3. context.Background(),
  4. http.WithMiddleware(
  5. circuitbreaker.Client(),
  6. ),
  7. http.WithEndpoint("127.0.0.1:8000"),
  8. )
  9. // grpc
  10. conn,err := transgrpc.Dial(
  11. context.Background(),
  12. grpc.WithMiddleware(
  13. circuitbreaker.Client(),
  14. ),
  15. grpc.WithEndpoint("127.0.0.1:9000"),
  16. )

Trigger circuit breaker

When the breaker is triggered, the client call for this Operation fails quickly for a period of time and returns the error ErrNotAllowed immediately,which defined as follows:

  1. // ErrNotAllowed is request failed due to circuit breaker triggered.
  2. var ErrNotAllowed = errors.New(503, "CIRCUITBREAKER", "request failed due to circuit breaker triggered")