Home Backend Development Golang How to use GRPC in Go?

How to use GRPC in Go?

May 10, 2023 pm 02:03 PM
go use grpc

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? Apr 26, 2024 am 09:40 AM

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

How to use gRPC to implement file upload in Golang? How to use gRPC to implement file upload in Golang? Jun 03, 2024 pm 04:54 PM

How to implement file upload using gRPC? Create supporting service definitions, including request and response messages. On the client, the file to be uploaded is opened and split into chunks, then streamed to the server via a gRPC stream. On the server side, file chunks are received and stored into a file. The server sends a response after the file upload is completed to indicate whether the upload was successful.

How to send Go WebSocket messages? How to send Go WebSocket messages? Jun 03, 2024 pm 04:53 PM

In Go, WebSocket messages can be sent using the gorilla/websocket package. Specific steps: Establish a WebSocket connection. Send a text message: Call WriteMessage(websocket.TextMessage,[]byte("Message")). Send a binary message: call WriteMessage(websocket.BinaryMessage,[]byte{1,2,3}).

How to match timestamps using regular expressions in Go? How to match timestamps using regular expressions in Go? Jun 02, 2024 am 09:00 AM

In Go, you can use regular expressions to match timestamps: compile a regular expression string, such as the one used to match ISO8601 timestamps: ^\d{4}-\d{2}-\d{2}T \d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-][0-9]{2}:[0-9]{2})$ . Use the regexp.MatchString function to check if a string matches a regular expression.

The difference between Golang and Go language The difference between Golang and Go language May 31, 2024 pm 08:10 PM

Go and the Go language are different entities with different characteristics. Go (also known as Golang) is known for its concurrency, fast compilation speed, memory management, and cross-platform advantages. Disadvantages of the Go language include a less rich ecosystem than other languages, a stricter syntax, and a lack of dynamic typing.

How to avoid memory leaks in Golang technical performance optimization? How to avoid memory leaks in Golang technical performance optimization? Jun 04, 2024 pm 12:27 PM

Memory leaks can cause Go program memory to continuously increase by: closing resources that are no longer in use, such as files, network connections, and database connections. Use weak references to prevent memory leaks and target objects for garbage collection when they are no longer strongly referenced. Using go coroutine, the coroutine stack memory will be automatically released when exiting to avoid memory leaks.

What is Bitget Launchpool? How to use Bitget Launchpool? What is Bitget Launchpool? How to use Bitget Launchpool? Jun 07, 2024 pm 12:06 PM

BitgetLaunchpool is a dynamic platform designed for all cryptocurrency enthusiasts. BitgetLaunchpool stands out with its unique offering. Here, you can stake your tokens to unlock more rewards, including airdrops, high returns, and a generous prize pool exclusive to early participants. What is BitgetLaunchpool? BitgetLaunchpool is a cryptocurrency platform where tokens can be staked and earned with user-friendly terms and conditions. By investing BGB or other tokens in Launchpool, users have the opportunity to receive free airdrops, earnings and participate in generous bonus pools. The income from pledged assets is calculated within T+1 hours, and the rewards are based on

A guide to unit testing Go concurrent functions A guide to unit testing Go concurrent functions May 03, 2024 am 10:54 AM

Unit testing concurrent functions is critical as this helps ensure their correct behavior in a concurrent environment. Fundamental principles such as mutual exclusion, synchronization, and isolation must be considered when testing concurrent functions. Concurrent functions can be unit tested by simulating, testing race conditions, and verifying results.

See all articles