我如何获得在grpc-java中调用的rpc方法的注释 [英] How can I get annotations on rpc method being called in grpc-java

查看:111
本文介绍了我如何获得在grpc-java中调用的rpc方法的注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;
        }
    }
}

并在rpc方法之前添加自定义注释

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);
    }
}

但是我发现我找不到在gRPC ServerInterceptor中获取注释信息的方法.有什么办法可以实现像这样的grpc请求验证吗?

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?

推荐答案

只需使用简单的ServerInterceptor,就可以完全不用批注来完成此操作:

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;
  }
}

请注意,我在这里跳过了大部分样板.当请求进入时,拦截器首先获取它,并检查其是否符合预期的方法.如果是这样,它将进行额外的验证.在生成的代码中,您可以引用现有的 MethodDescriptor ,而不是像上面那样复制名称.

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 MethodDescriptors rather than copying the name out like above.

这篇关于我如何获得在grpc-java中调用的rpc方法的注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆