When accessing gRPC services running on the same server, it's unnecessary to establish separate connections for each service. A single grpc.ClientConn can be utilized to access all services.
To share a connection, create a grpc.ClientConn using the desired endpoint and pass it to the pb.New*Client() functions for each service you wish to use. This allows them to utilize the same connections.
<code class="go">cc, err := grpc.Dial("localhost:6000", grpc.WithInsecure()) if err != nil { log.Fatal(err) } c1 := pb.NewSubscriberServiceClient(cc) c2 := pb.NewDropperServiceClient(cc)</code>
Although you could create an interface to combine client-side gRPC functions for multiple services, the generated code in pb.go handles all essential operations. Implementing new functionality is only necessary for specific custom logic.
For services with unique method names, you can define a convenience struct to bundle their clients:
<code class="go">type SubscriberDropper struct { pb.SubscriberServiceClient pb.DropperServiceClient }</code>
Accessing multiple gRPC services over a single connection simplifies client-side implementation and improves code maintainability.
The above is the detailed content of How to Access Multiple gRPC Services Over a Single Connection?. For more information, please follow other related articles on the PHP Chinese website!