Share data between interceptor and service gRPC

Let’s imagine that we need to pass data between the interceptor and the service (or we need to sharedata between the interceptor and the service, or we need to exchange data between the interceptor and the service).

We have a service:

public class YourServiceImpl extends YourService.YourServiceImplBase {
  @Override 
  public void yourMethod() {
    ...
  }
}

We have the code for starting the gRPC server:

Server server = ServerBuilder
                
    .forPort(1234)
             
    .addService(new YourServiceImpl())
              
    .build();

server.start();
server.awaitTermination();

In your Interceptor class, in interceptCall() method you need to create Context and return Context.interceptCall():

class Interceptor implements ServerInterceptor {
  public final Context.Key<String> SHARED_DATA = Context.key("shareData"); 
  private String dataToShare;

  @Override
        
  public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call,
Metadata headers, ServerCallHandler<ReqT, RespT> next) {
            
    dataToShare = "mySharedData!!"
    Context context = Context.current().withValue(SHARED_DATA, dataToShare)
            
    return Contexts.interceptCall(context, call, headers, next);
        
  }
}

Let’s use the interceptor object in the service:

public class YourServiceImpl extends YourService.YourServiceImplBase {
  Interceptor interceptor;

  public YourServiceImpl(Interceptor interceptor) {
    this.interceptor = interceptor;
  }

  @Override 
  public void yourMethod() {
    System.out.println("Data from interceptor: " + interceptor.SHARED_DATA.get());
  }
}

And let’s register your interceptor in the gRPC server launch code:

Interceptor interceptor = new Interceptor();
Server server = ServerBuilder
              
    .forPort(1234)
              
    .addService(new YourServiceImpl(interceptor))
    .intercept(interceptor)
              
    .build();

server.start();

server.awaitTermination();
Telegram channel

If you still have any questions, feel free to ask me in the comments under this article or write me at promark33@gmail.com.

If I saved your day, you can support me 🤝

9 thoughts on “Share data between interceptor and service gRPC

  1. Pingback: spironolactone 8nv

Leave a Reply

Your email address will not be published. Required fields are marked *