1
0
mirror of https://github.com/go-micro/go-micro.git synced 2025-01-17 17:44:30 +02:00

Hystrix filter (#2286)

* support hystrix filter

* filter function should return true of false
This commit is contained in:
Johnson C 2021-09-28 18:23:04 +08:00 committed by GitHub
parent 8c39b1e120
commit 44ecd6a457
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 12 additions and 7 deletions

View File

@ -9,7 +9,7 @@ import (
type clientWrapper struct { type clientWrapper struct {
client.Client client.Client
filter func(context.Context, error) error filter func(context.Context, error) bool
fallback func(context.Context, error) error fallback func(context.Context, error) error
} }
@ -19,7 +19,9 @@ func (cw *clientWrapper) Call(ctx context.Context, req client.Request, rsp inter
err = cw.Client.Call(c, req, rsp, opts...) err = cw.Client.Call(c, req, rsp, opts...)
if cw.filter != nil { if cw.filter != nil {
// custom error handling, filter errors that should not trigger circuit breaker // custom error handling, filter errors that should not trigger circuit breaker
return cw.filter(ctx, err) if cw.filter(ctx, err) {
return nil
}
} }
return err return err
}, cw.fallback) }, cw.fallback)

View File

@ -50,12 +50,12 @@ func TestBreakerWithFilter(t *testing.T) {
s := selector.NewSelector(selector.Registry(r)) s := selector.NewSelector(selector.Registry(r))
c := client.NewClient( c := client.NewClient(
client.Selector(s), client.Selector(s),
client.Wrap(NewClientWrapper(WithFilter(func(c context.Context, e error) error { client.Wrap(NewClientWrapper(WithFilter(func(c context.Context, e error) bool {
var merr *merrors.Error var merr *merrors.Error
if errors.As(e, &merr) && merr.Detail == "service test.service: not found" { if errors.As(e, &merr) && merr.Detail == "service test.service: not found" {
return nil return true
} }
return e return false
}))), }))),
) )

View File

@ -4,7 +4,10 @@ import "context"
// Options represents hystrix client wrapper options // Options represents hystrix client wrapper options
type Options struct { type Options struct {
Filter func(context.Context, error) error // Filter used to prevent errors from trigger circuit breaker.
// return true if you want to ignore target error
Filter func(context.Context, error) bool
// Fallback used to define some code to execute during outages.
Fallback func(context.Context, error) error Fallback func(context.Context, error) error
} }
@ -12,7 +15,7 @@ type Options struct {
type Option func(*Options) type Option func(*Options)
// WithFilter used to set filter func for options // WithFilter used to set filter func for options
func WithFilter(filter func(context.Context, error) error) Option { func WithFilter(filter func(context.Context, error) bool) Option {
return func(o *Options) { return func(o *Options) {
o.Filter = filter o.Filter = filter
} }