Last active
February 28, 2019 16:20
-
-
Save vtolstov/bf0ab52a06c81793707fbd4a132cd7d3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package breaker | |
import ( | |
"context" | |
"sync" | |
"github.com/micro/go-micro/client" | |
"github.com/micro/go-micro/errors" | |
"github.com/sony/gobreaker" | |
) | |
type clientWrapper struct { | |
bs gobreaker.Settings | |
cbs map[string]*gobreaker.CircuitBreaker | |
mu sync.Mutex | |
client.Client | |
} | |
func (c *clientWrapper) Call(ctx context.Context, req client.Request, rsp interface{}, opts ...client.CallOption) error { | |
svc := req.Service() + "." + req.Endpoint() | |
c.mu.Lock() | |
cb, ok := c.cbs[svc] | |
if !ok { | |
cb = gobreaker.NewCircuitBreaker(c.bs) | |
c.cbs[svc] = cb | |
} | |
c.mu.Unlock() | |
_, err := cb.Execute(func() (interface{}, error) { | |
cerr := c.Client.Call(ctx, req, rsp, opts...) | |
return nil, cerr | |
}) | |
if err != nil { | |
err = errors.New(req.Service(), err.Error(), 503) | |
} | |
return err | |
} | |
// NewClientWrapper takes a gobreaker.Settings and returns a client Wrapper. | |
func NewClientWrapper(bs gobreaker.Settings) client.Wrapper { | |
return func(c client.Client) client.Client { | |
w := &clientWrapper{} | |
w.bs = bs | |
w.cbs = make(map[string]*gobreaker.CircuitBreaker) | |
w.Client = c | |
return w | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment