Tando
Tando

Reputation: 845

How can I catch all the incoming gRPC messages in Java?

For example, you can receive bidirectional streaming incoming messages with the following code.


public class DataService extends DataServiceGrpc.DataServiceImplBase {
    @Override
    public StreamObserver<DataReq> send(StreamObserver<DataResp> responseObserver) {
        return new StreamObserver<DataReq>() {
            @Override
            public void onNext(DataReq value) {
            }

            @Override
            public void onError(Throwable t) {
            }

            @Override
            public void onCompleted() {
            }
        };
    }
}

And say I have some other classes like this to catch each in-coming gRPC messages.

If I want to capture and control all the in-coming messages before these classes receive them, what is the standard way to achieve the goal?

Upvotes: 2

Views: 614

Answers (1)

Eric Anderson
Eric Anderson

Reputation: 26434

StreamObserver is part of the stub, so no. But you can make a ServerInterceptor and register it with serverBuilder.intercept(). The interceptor can see every incoming message by wrapping the ServerCall.Listener.

class MyInterceptor implements ServerInterceptor {
  @Override
  public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
      ServerCall<ReqT,RespT> call, Metadata headers, ServerCallHandler<ReqT,RespT> next)
    return new SimpleForwardingServerCallListener<>(next.startCall(call, headers)) {
      @Override public void onMessage(ReqT message) {
        // your code here

        super.onMessage(message); // call into the application
      }
    };
  }
}

next would end up being another interceptor or the application. The generated code (e.g., DataServiceImplBase) implements ServerCallHandler and has it call the application (e.g., DataService.send()). So this interceptor can run before the application runs.

Upvotes: 3

Related Questions