如何在GRPC拦截器中访问消息请求?

2022-04-03 00:00:00 rpc grpc java interceptor
我想在服务器端为多个方法使用相同的拦截器 因为它们都有相同的请求类型(StateRequest):

rpc apply (StateRequest) returns (StateResponse) {} 
rpc cancel (StateRequest) returns (StateResponse) {}
rpc remove (StateRequest) returns (StateResponse) {}
rpc development (StateRequest) returns (StateResponse) {}
rpc implement (StateRequest) returns (StateResponse) {}
rpc draft (StateRequest) returns (StateResponse) {}

拦截器:

public class ServerUserRoleAuthInterceptor implements ServerInterceptor {

    @Override
    public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
        ServerCall<ReqT, RespT> call,
        Metadata headers,
        ServerCallHandler<ReqT, RespT> next) {
        String callName = call.getMethodDescriptor().getFullMethodName();
        logger.info("Call: {}", callName);

        // TODO: validate request (`StateRequest` instance)

        return next.startCall(call, headers);
    }
}

我该怎么做?


解决方案

您需要在Listener上观察onMessage(ReqT)回调。

return new SimpleForwardingServerCallListener<ReqT>(next.startCall(call, headers)) {
  @Override 
  public void onMessage(ReqT request) {
    // TODO:validate request
    super.onMessage(request);
  }
};

相关文章