Search code examples
grpcrpc

Can different grpc methods share a same stub and a same channel


I'm developing a distributed backend system and I used gRPC as the method of communicaiton.

Let's say that I have such a proto file.

service Greeter {
  rpc SayHello (HelloRequest) returns (HelloReply) {}
  rpc SayHello2 (HelloRequest) returns (stream HelloReply) {}
  rpc SayHello3 (stream HelloRequest) returns (HelloReply) {}
}

I've known that we need to create channels and stubs to call gRPC methods.

But I don't know if different methods could use a same stub and a same channel.

I've read the official doc: https://grpc.io/docs/guides/performance/

It says

Always re-use stubs and channels when possible.

But I'm not sure if the methods in the service Greeter could/should share a same stub and a channel as one of them is Unary RPC and others are server/client streaming RPC.


Solution

  • Yes, it is supported (and recommended) to reuse the same stub. You can also use the same channel for multiple stubs, this will save you some overhead, especially for secure connections.