Home  >  Article  >  Backend Development  >  Can I Access Multiple gRPC Services with a Single Connection?

Can I Access Multiple gRPC Services with a Single Connection?

Susan Sarandon
Susan SarandonOriginal
2024-11-03 03:42:31162browse

Can I Access Multiple gRPC Services with a Single Connection?

Access Multiple gRPC Services Simultaneously

Problem:

In a server with multiple gRPC services available on a single port, why is it necessary to establish separate connections for each service when dialing from the client?

<code class="go">func NewSubscriber() (c SubscriberRPC, err error) {
    c.conn, err = grpc.Dial("localhost:6000", grpc.WithInsecure())
    if err != nil {
        log.Fatal(err)
    }
    c.client = pb.NewSubscriberServiceClient(c.conn)
    return
}

func NewDropper() (c DropperRPC, err error) {
    c.conn, err = grpc.Dial("localhost:6000", grpc.WithInsecure())
    if err != nil {
        log.Fatal(err)
    }
    c.client = pb.NewDropperServiceClient(c.conn)
    return
}</code>

Resolution:

Contrary to the initial assumption, multiple gRPC services on the same server can be accessed with a single connection. This can be achieved by creating one grpc.ClientConn and passing it to multiple pb.New*Client functions.

<code class="go">func main() {
    cc, err := grpc.Dial("localhost:6000", grpc.WithInsecure())
    if err != nil {
        log.Fatal(err)
    }
    c1 := pb.NewSubscriberServiceClient(cc)
    c2 := pb.NewDropperServiceClient(cc)
}</code>

Using an Interface:

Customizing the client-side experience is possible using the generated code provided in the pb.go file. However, the generated code already handles all the necessary RPC functionality.

For convenience, multiple services can be combined into a single struct:

<code class="go">type SubscriberDropper struct {
    pb.SubscriberServiceClient
    pb.DropperServiceClient
}

func main() {
    // ... as above ...
    sd := &SubscriberDropper{c1, c2}
}</code>

The above is the detailed content of Can I Access Multiple gRPC Services with a Single Connection?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn