How to use GRPC in Go?

王林
Release: 2023-05-10 14:03:06
forward
2544 people have browsed it

With the continuous development of modern applications, the requirements for high performance and scalability are also getting higher and higher. Therefore, there is a distributed architecture based on the RPC protocol to meet these needs. GRPC is an open source framework based on Google's internal StuB. GRPC provides a highly scalable mechanism for communication across programming languages, designed to efficiently manage standardized communication between applications.

This article will introduce how to use GRPC in Go. We will cover the concept of GRPC, the steps to communicate using GRPC, and an example of implementing a simple GRPC service in Go.

The concept of GRPC

GRPC is an RPC framework based on HTTP/2, using protobuf as the default data serialization method. This means it can easily enable communication between different languages ​​(leveraging generated code and middleware provided by grpc).

Extensibility: GRPC can implement simple and complex authentication and authorization logic at the code stream and connection layer, and can collaborate with modern computing platforms such as Kubernetes.

Communicating using GRPC

In this section, we will introduce the detailed steps for communicating using GRPC. In this article, we will implement a simple GRPC service using Go language.

Step 1: Define protobuf file

First, we need to define our protobuf file to declare our interface. In this example, we define a simple service that adds two numbers. The following is the content of our .proto file:

syntax = "proto3";

option go_package = ".;main";

package calculator;

message AddRequest {
    int32 x = 1;
    int32 y = 2;
}

message AddResponse {
    int32 result = 1;
}

service Calculator {
    rpc Add(AddRequest) returns (AddResponse);
}
Copy after login

In this protobuf file, we define two messages, AddRequest and AddResponse, and a service interface Calculator, which provides an Add method that receives Takes two numbers as arguments and returns their sum.

Step 2: Generate GO code

Next, we need to use the protoc tool to generate GO code. We can generate code in the following way:

protoc --go_out=plugins=grpc:. *.proto
Copy after login
Copy after login

This command will generate a calculator.pb.go file, which contains the GO code for the services and messages we defined.

Step 3: Implement the server side

On the server side, we need to implement a service for the interface we defined. In our case, our service is just a simple addition service that adds two numbers and returns their sum. The following is our server code:

package main

import (
    "context"
    "net"
    "google.golang.org/grpc"
    pb "github.com/calculator"
)

type server struct{}

func (s *server) Add(ctx context.Context, req *pb.AddRequest) (*pb.AddResponse, error) {
    result := req.X + req.Y
    return &pb.AddResponse{Result:result}, nil
}

func main() {
    l, err := net.Listen("tcp", ":8080")
    if err != nil {
        panic(err)
    }
    s := grpc.NewServer()

    pb.RegisterCalculatorServer(s, &server{})

    err = s.Serve(l)
    if err != nil {
        panic(err)
    }
}
Copy after login

We first define a structure named "server" and add an Add method to it. This method will receive two numbers x and y, calculate their sum, and return an AddResponse as the response object.

We also define a main function in which we create a new grpc service and bind it to the local address of port 8080. We also inject the service we defined into the grpc server and start the grpc server.

Step 4: Implement the client

Finally, we need to write a client code that can send requests to our server and receive responses. Please note that the .proto files in client and server side code must match. Below is our client code:

package main

import (
    "context"
    "fmt"
    "google.golang.org/grpc"
    pb "github.com/calculator"
)

func main() {
    conn, err := grpc.Dial(":8080", grpc.WithInsecure())
    if err != nil {
        panic(err)
    }

    client := pb.NewCalculatorClient(conn)

    req := pb.AddRequest{X:2, Y:3}
    resp, err := client.Add(context.Background(), &req)
    if err != nil {
        panic(err)
    }

    fmt.Printf("Result: %d", resp.Result)
}
Copy after login

In this client code, we first create a connection to the GRPC server and then use this connection to create a new client. Next, we create an AddRequest, set its values ​​to 2 and 3, and send the request to the server. Finally, we receive and print the server's response.

How to run the sample code

To run our sample code, we need to first set up the Go development environment and install related dependencies. Suppose our code package is named main. To run our example code locally, you need to execute the following command first:

go get -u google.golang.org/grpc
go get -u github.com/golang/protobuf/protoc-gen-go
Copy after login

Next run the protoc command to generate go code:

protoc --go_out=plugins=grpc:. *.proto
Copy after login
Copy after login

Then compile our service and client code, and compile them respectively Start them:

go build server.go
go build client.go
./server
./client
Copy after login

If everything goes well, the client will send an addition request to the GRPC server and display the result as 5.

Conclusion

This article introduces how to use GRPC in Go language. We first discussed the concept of GRPC, and then demonstrated how to use protobuf to define interface specifications, how to generate GO code, and how to implement a simple GRPC service. By using these steps, you can start using GRPC in Go to implement high-performance and scalable distributed systems.

The above is the detailed content of How to use GRPC in Go?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template