Add grpc retry (#1160)
* Add grpc retry * Update grpc retry * Add tests * Fix a bug * Add api && some tests * Add comment * Add double check * Add server retry quota * Update optimize code * Fix bug * Update optimize code * Update optimize code * Fix bug
This commit is contained in:
19
zrpc/internal/clientinterceptors/retryinterceptor.go
Normal file
19
zrpc/internal/clientinterceptors/retryinterceptor.go
Normal file
@@ -0,0 +1,19 @@
|
||||
package clientinterceptors
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/tal-tech/go-zero/core/retry"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
// RetryInterceptor retry interceptor
|
||||
func RetryInterceptor(enable bool) grpc.UnaryClientInterceptor {
|
||||
return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
|
||||
if !enable {
|
||||
return invoker(ctx, method, req, reply, cc, opts...)
|
||||
}
|
||||
return retry.Do(ctx, func(ctx context.Context, callOpts ...grpc.CallOption) error {
|
||||
return invoker(ctx, method, req, reply, cc, callOpts...)
|
||||
}, opts...)
|
||||
}
|
||||
}
|
||||
27
zrpc/internal/clientinterceptors/retryinterceptor_test.go
Normal file
27
zrpc/internal/clientinterceptors/retryinterceptor_test.go
Normal file
@@ -0,0 +1,27 @@
|
||||
package clientinterceptors
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/tal-tech/go-zero/core/retry"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRetryInterceptor_WithMax(t *testing.T) {
|
||||
n := 4
|
||||
for i := 0; i < n; i++ {
|
||||
count := 0
|
||||
cc := new(grpc.ClientConn)
|
||||
err := RetryInterceptor(true)(context.Background(), "/1", nil, nil, cc,
|
||||
func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, opts ...grpc.CallOption) error {
|
||||
count++
|
||||
return status.Error(codes.ResourceExhausted, "ResourceExhausted")
|
||||
}, retry.WithMax(i))
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, i+1, count)
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user