Background of 0.

Write an example of gRPC.

1. The introduction of gRPC

GRPC is Google’s open source lightweight RPC communication framework, whose communication protocol is based on binary data flow, which makes gRPC have excellent performance.

GRPC uses protobuf as the communication protocol

The communication between the two microservices is based on HTTP 2.0 binary data frames, using the protobuf protocol built into gRPC, whose DSL syntax can clearly define the data structure of the communication between services

Procedure decomposition to implement a gRPC call requires the following steps:

  • (1) Define data structures and service methods: define services in a.proto file.
  • (2) Generate interface source code: use the Protocol Buffer compiler to generate server and client code.
  • (3) Server implementation interface client call: use Go API to achieve a simple client and server.

1. The implementation

  • (1) Write a.proto file that defines data structures and service methods.
  • (2) Generate server and client code with the Protocol Buffer compiler.
  • (3) Realize the server.
  • (3) to achieve a simple client.

Let’s break it down

1.1 Define data structures and service methods

Write a.proto file that defines data results and service methods, as shown in the following example:

syntax = "proto3"; Service Greeter {RPC SayHello (HelloRequest) returns (HelloReply) {}} string name = 1; } // Response message HelloReply {string message = 1; }Copy the code

1.2 Server implementation

Execute protoc to generate source code.

protoc --go_out=plugins=grpc:. helloworld/helloworld.proto
Copy the code

When you’re done, make sure the generated source code goes into your project.

1.3 Server implementation

The steps are as follows:

  • (1) Implement the method declared above
  • (2) Use net.Listen to establish TCP listening
  • Create a grpc.NewServer server object.
  • (3) Execute the Serve function of the server object
package main import ( context "context" "fmt" "google.golang.org/grpc" "google.golang.org/grpc/examples/helloworld/helloworld" pb "grpcdemo/helloworld" "log" "net" ) type myServer struct { The helloworld. UnimplementedGreeterServer} / / port const (port = ": 50051")/implementing an interface * / * * func (* myServer) that contains your application SayHello (CTX context.Context, req *pb.HelloRequest) (*pb.HelloReply, error) { log.Printf("Received: %v", req.GetName()) reply := pb.HelloReply{Message: "Hello "+ req.getName ()} return &reply, nil} func main() {// Prepare a TCP listener listener1, err := net.listen (" TCP ", port) if err ! = nil {log.fatalf (" error: %v", err)} // Build a GRPC server server1 := grpc.newServer () pb.registerGreeterServer (server1, Printf(" service start %v\n", port) err = Server1. Serve(listener1) if err! = nil {log.fatalf (" Failed to start server: %v", err)}}Copy the code

1.4 Client implementation

The steps are as follows:

  • (1) Use grpc.Dial to establish a connection with the server
  • (2) Use pb.NewGreeterClient(CONN) to create a stub proxy object for the client.
  • (3) Execute the method to be called
Package main import ("context" "FMT" "google.golang.org/grpc" pb "grpcdemo/ helloWorld ""log" "time") address = "localhost:50051" defaultName = "world" ) func main() { conn, err := grpc.Dial(address, grpc.WithInsecure(), grpc.WithBlock()) if err ! = nil {log.fatalf (" connection failed: %v", err)} defer conn.close () // Get a stub client that called the method := pb.newGreeterClient (conn) // Prepare a timeout processing CTX, Cancel := context.withtimeout (context.background (), time.second) defer cancel() // invoke fmt.println (" invoke ") reply, err := client.SayHello(ctx, &pb.HelloRequest{Name: "zhang3"}) if err ! = nil {log.fatalf (" call failed: %v", err)} log.printf (" result: %s", reply.getMessage ())}Copy the code

Demo Results:

\

image.png

Reference 2.

www.jianshu.com/p/dd27a7513…

Doc.oschina.net/grpc?t=6013…