gRPC service interceptor share
What's inside this article
⌄
- Share data between interceptor and service gRPC
- GRPC interceptor service communication
- GRPC send data service interceptor
Let’s imagine that we need to pass data between the interceptor and the service (or we need to share data between the interceptor and the service, or we need to exchange data between the interceptor and the service).
We have a service YourServiceImpl.java:
public class YourServiceImpl extends YourService.YourServiceImplBase {
@Override
public void yourMethod() {
...
}
We have the code for starting the gRPC server GRPCServer.java:
Server server = ServerBuilder
.forPort(1234)
.addService(new YourServiceImpl())
.build();
server.start();
server.awaitTermination();
In your Interceptor.java 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 YourServiceImpl.java:
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();