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

Can I Access Multiple gRPC Services with a Single Connection?

Susan Sarandon
Release: 2024-11-03 03:42:31
Original
290 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template