简体   繁体   English

如何获取在grpc-java中调用的rpc方法的注释

[英]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. 我需要在使用不同的验证程序调用不同的rpc方法之前先验证请求。

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 并在我的rpc方法之前添加自定义注释

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. 但是我发现我找不到在gRPC ServerInterceptor中获取注释信息的方法。 Is there any way to implement grpc request validation like this? 有什么办法可以实现像这样的grpc请求验证吗?

You can accomplish this without having the annotation at all, and just using a plain ServerInterceptor: 您可以完全不用注释,而只需使用简单的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. 在生成的代码中,您可以引用现有的MethodDescriptor而不是像上面那样复制名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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