I am learning to use grpc recently and feel confused about one thing after I instantiated a Server class named server:
server = ServerBuilder.forPort(port)
.addService(new MetadataStoreImpl(this.config, port))
.executor(Executors.newFixedThreadPool(numThreads))
.build()
.start();
I read the java doc and found the ServerBuilder.addService:
public abstract T addService(ServerServiceDefinition service);
In this case, I use my own class "MetadataStoreImpl" to replace "ServerServiceDefinition" but still don't know why. Moreover,how can I get reference the member variable of this MetadataStoreImpl class from class server? Could anyone help me?
If your MetadataStoreImpl
extends a generated service stub (e.g., MetadataStoreImplBase
) then it will implement gRPC's BindableService
interface. ServerBuilder
has another addService
method that accepts a BindableService
instead of a ServerServiceDefinition
. Here is an example of our generated code's implementation of the bindService
method, which just builds and returns a ServerServiceDefinition
.
For your second question, you can get a list of ServerServiceDefinitions
via Server#getServices
, but this won't directly give you back your original MetadataStoreImpl
, but rather the ServerServiceDefinition
returned by the generated code's bindService
method. Typically, you wouldn't use getServices
, as you'd just retain a reference to your service after you added it to the builder.
You can find more information gRPC Java's generated code at https://grpc.io/docs/reference/java/generated-code.html.