【问题标题】:How can I get annotations on rpc method being called in grpc-java如何获取在 grpc-java 中调用的 rpc 方法的注释
【发布时间】:2016-12-11 18:18:49
【问题描述】:

我需要在使用不同的验证器调用不同的 rpc 方法之前验证请求。

所以我实现了类似的验证器

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

并在我的 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);
    }
}

但是我发现在gRPC ServerInterceptor中找不到获取注解信息的方法。有没有办法像这样实现 grpc 请求验证?

【问题讨论】:

    标签: java reflection annotations grpc grpc-java


    【解决方案1】:

    您完全可以在没有注释的情况下完成此操作,只需使用普通的 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;
      }
    }
    

    请注意,我在这里跳过了大部分样板文件。当一个请求进来时,拦截器首先得到它并检查它是否符合它所期望的方法。如果是这样,它会进行额外的验证。在生成的代码中,您可以引用现有的MethodDescriptors,而不是像上面那样复制名称。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-12
      相关资源
      最近更新 更多