简体   繁体   中英

How can I get annotations on rpc method being called in grpc-java

I need to validate request before different rpc methods being called with different validators.

So I implemented validators like

class BarRequestValidator {
    public FooServiceError validate(BarRequest request) {
        if (request.bar.length > 12) {
            return FooServiceError.BAR_TOO_LONG;
        } else {
            return null;
        }
    }
}

and add a custom annotation before my rpc method

class FooService extends FooServiceGrpc.FooServiceImplBase {
    @Validated(validator = BarRequestValidator.class)
    public void bar(BarRequest request, StreamObserver<BarResponse> responseObserver) {
        // Validator should be executed before this line, and returns error once validation fails.
        assert(request.bar <= 12);
    }
}

But I found that I can't find a way to get annotation information in gRPC ServerInterceptor. Is there any way to implement grpc request validation like this?

You can accomplish this without having the annotation at all, and just using a plain ServerInterceptor:

Server s = ServerBuilder.forPort(...)
    .addService(ServerInterceptors.intercept(myService, myValidator))
    ...

private final class MyValidator implements ServerInterceptor {
  ServerCall.Listener interceptCall(call, headers, next) {
    ServerCall.Listener listener = next.startCall(call, headers);
    if (call.getMethodDescriptor().getFullMethodName().equals("service/method")) {
      listener = new SimpleForwardingServerCallListener(listener) {
        @Override
        void onMessage(request) {
          validate(request);
        }
      }
    }
    return listener;
  }
}

Note that I'm skipping most of the boilerplate here. When a request comes in, the interceptor gets it first and checks to see if its for the method it was expecting. If so, it does extra validation. In the generated code you can reference the existing MethodDescriptor s rather than copying the name out like above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM