Home  >  Article  >  Backend Development  >  How to use gRPC to implement basic server and client in Golang

How to use gRPC to implement basic server and client in Golang

PHPz
PHPzOriginal
2023-03-31 10:26:141960browse

gRPC is a high-performance, open source and universal remote procedure call framework suitable for RPC calls across languages ​​and platforms. It uses the protobuf protocol developed by Google for data transmission, can quickly realize communication between the server and the client, and provides rich functions and scalability. This article will introduce how to use gRPC to implement basic servers and clients in Golang.

1. Install gRPC

Before we start, we need to install gRPC and protobuf first. You can use the following command:

$ go get -u google.golang.org/grpc
$ go get -u github.com/golang/protobuf/protoc-gen-go

2. Create protobuf file

Next we need to create a .proto file, which defines the data we will transfer and the method to call. In this example, we created a file called greet.proto.

syntax = "proto3";

package greet;

service GreetService {
  rpc SayHello (HelloRequest) returns (HelloResponse) {}
}

message HelloRequest {
  string name = 1;
}

message HelloResponse {
  string message = 1;
}

3. Generate code

Generate gRPC related code through protobuf file. Run the following command:

$ protoc -I greet/ greet/greet.proto --go_out=plugins=grpc:greet

The generated code will be saved in the greet directory.

4. Implement the server side

In the server side implementation, we need to implement the service interface defined in the proto file. We can complete the server-side code implementation through the following steps:

  • Create a gRPC server
  • Register the service
  • Run the server

The following is the code implementation:

package main

import (
    "context"
    "log"
    "net"

    "google.golang.org/grpc"
    pb "path/to/greet"
)

type server struct {}

func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloResponse, error) {
    return &pb.HelloResponse{Message: "Hello " + in.Name}, nil
}

func main() {
    lis, err := net.Listen("tcp", ":50051")
    if err != nil {
        log.Fatalf("failed to listen: %v", err)
    }
    s := grpc.NewServer()
    pb.RegisterGreetServiceServer(s, &server{})
    if err := s.Serve(lis); err != nil {
        log.Fatalf("failed to serve: %v", err)
    }
}

5. Implement the client

The client implementation is relatively simple. We only need to connect to the corresponding server and instantiate the client, and then we can call the methods provided by the server. In the client code implementation, you need to first create a connection for gRPC communication, then use the connection to create a client and call the interface method.

The following is the implementation of the client code:

package main

import (
    "log"
    "os"
    "context"
    "google.golang.org/grpc"
    pb "path/to/greet"
)

func main() {
    address := "localhost:50051"
    if len(os.Args) > 1 {
        address = os.Args[1]
    }
    conn, err := grpc.Dial(address, grpc.WithInsecure())
    if err != nil {
        log.Fatalf("couldn't connect: %v", err)
    }
    defer conn.Close()

    c := pb.NewGreetServiceClient(conn)

    name := "world"
    if len(os.Args) > 2 {
        name = os.Args[2]
    }
    r, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: name})
    if err != nil {
        log.Fatalf("error: %v", err)
    }
    log.Printf("Greeting: %s", r.Message)
}

6. Test

We have implemented the server and client code, now run the server, and then start the client Come and test.

$ go run greet_server.go

After running the server, open a terminal and run the client to test:

$ go run greet_client.go
Greeting: Hello world

7. Summary

This article introduces how to use gRPC to implement basics in Golang server and client. gRPC provides powerful encoding and decoding capabilities while supporting multiple transport formats, including JSON and protocol buffer data, making it suitable for various types of applications. For example, distributed systems, large-scale web applications and games, etc. If you want to learn more about gRPC, check out the official documentation.

The above is the detailed content of How to use gRPC to implement basic server and client in Golang. 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