Introduction:
gRPC allows clients to communicate with multiple services exposed on a single server. However, it's often assumed that each service requires a dedicated client connection. This article explores how to utilize a single connection to access multiple gRPC services.
Dialing a Single Socket:
Despite having separate service interfaces, it's unnecessary to establish individual socket connections for each service. Instead, you can create a single grpc.ClientConn. This connection can then be passed to all service clients instantiated using the New*Client() functions. By sharing a connection, these clients leverage the same underlying transport and multiplexing mechanisms.
<code class="go">cc, err := grpc.Dial("localhost:6000", grpc.WithInsecure()) if err != nil { log.Fatal(err) }</code>
Using an Interface:
Although creating separate structs for each service simplifies client interactions, it promotes code duplication. To reduce this, an interface, such as ServiceClient, can be defined and implemented by all service clients. This enables the sharing of common properties and methods, reducing code clutter.
<code class="go">type ServiceClient interface { // Common methods and properties } type SubscriberClient struct { pb.SubscriberServiceClient } type DropperClient struct { pb.DropperServiceClient }</code>
Eliminating Library Dependencies:
While libraries like cmux offer solutions for sharing connections, it's possible to achieve this without external dependencies. The grpc.ClientConn provides direct access to the underlying transport, enabling the creation of multiple service clients.
<code class="go">func NewServiceClient(conn *grpc.ClientConn, service interface{}) interface{} { switch service { case pb.SubscriberServiceServer: return pb.NewSubscriberServiceClient(conn) case pb.DropperServiceServer: return pb.NewDropperServiceClient(conn) } panic("Unknown service") }</code>
Key Takeaways:
The above is the detailed content of How can I access multiple gRPC services using a single connection?. For more information, please follow other related articles on the PHP Chinese website!