retryinterceptor.go 1010 B

1234567891011121314151617181920212223242526272829303132333435
  1. package serverinterceptors
  2. import (
  3. "context"
  4. "strconv"
  5. "github.com/tal-tech/go-zero/core/logx"
  6. "github.com/tal-tech/go-zero/core/retry"
  7. "google.golang.org/grpc"
  8. "google.golang.org/grpc/codes"
  9. "google.golang.org/grpc/metadata"
  10. "google.golang.org/grpc/status"
  11. )
  12. func RetryInterceptor(maxAttempt int) grpc.UnaryServerInterceptor {
  13. return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo,
  14. handler grpc.UnaryHandler) (resp interface{}, err error) {
  15. var md metadata.MD
  16. requestMd, ok := metadata.FromIncomingContext(ctx)
  17. if ok {
  18. md = requestMd.Copy()
  19. attemptMd := md.Get(retry.AttemptMetadataKey)
  20. if len(attemptMd) != 0 && attemptMd[0] != "" {
  21. if attempt, err := strconv.Atoi(attemptMd[0]); err == nil {
  22. if attempt > maxAttempt {
  23. logx.WithContext(ctx).Errorf("retries exceeded:%d, max retries:%d", attempt, maxAttempt)
  24. return nil, status.Error(codes.FailedPrecondition, "Retries exceeded")
  25. }
  26. }
  27. }
  28. }
  29. return handler(ctx, req)
  30. }
  31. }