[TOC]

gRPC

GRPC introduction

What is GRPC?

What is the difference between RPC and RESTful?

RPC messaging can be TCP, UDP, or HTTP, and when RPC messaging is HTTP, its structure is similar to that of a RESTful architecture

What is the difference between RPC and RESTful:

  • Different objects to operate on, RESTful will be more flexible

RPC operates on method objects; RESTful operates on resources

The client side and server side of RPC are tightly coupled. The client side needs to know the function name, parameter type and order of the server side before the remote procedure call can be made.

RESTful operates on resources semantically based on HTTP, and the order of parameters generally does not matter

  • RCP is more suitable for customization

    RESTful performs operations on resources, mainly CURD (add, delete, change and search) operations. If you need to implement a specific function, such as calculating the average score of a class, then it makes more sense to use RPC to define the server methods (such as: stu.calavg) for the client to call

What are the characteristics of GRPC?

  • GRPC can be developed across languages

The GRPC client can directly call remote programs on different servers. Using the gesture looks like calling local procedure calls, it is easy to build distributed applications and services. The client and the server can be implemented in different languages supported by GRPC, respectively.

  • Based on the HTTP2 standard design, there are some advantages over other frameworks

    • supportLong connection, two-way flow, header compression, multiplexing requestsEtc.
    • Save bandwidth,Reduce the number of TCP links,Save CPU usageandExtend battery life
    • Improved performance of cloud services and Web applications
    • The client and server interact transparently
    • By default, the GRPC uses ProtoBuf to serialize data

What is the data interaction mode of GRPC?

Request reply

The client makes a single request and can read a series of messages from the server

The client writes a series of messages to the server and waits for the server to respond

Both the client and the server can send a series of messages by reading and writing a stream of data

The method of serializing data – protobuf

ProtoBuf is a way to serialize data, such as JSON, XML, etc

A brief introduction to the three keywords contained in the structure definition of ProtoBuf

  • The.proto suffix, except for the structure definition, ends with a semicolon
  • The structure definition can contain three keywords: message, service, and enum
  • A semicolon at the end of an RPC method definition is optional

Message is humped and fields are lowercase and underlined

 message ServerRequest {
      required string my_name = 1;
  }

Enums type names are humped, and fields are named in uppercase and underlined letters

 enum MyNum {
      VALUE1 = 1;
      VALUE2 = 2;
  }

Service and RPC method names are humped

Service Love {// define Confession method RPC MyConfession(Request) returns (Response) {}}

For details on installing Prtobuf, check out the installation steps we wrote earlier, “Protobuf installation in 5 steps”.

The package name is declared in the proto file using the package keyword. By default, it is converted to the same package name in Go. You can customize the package name by modifying go_package:

test.proto

syntax = "proto3"; // Proto version package pb; // Specify the package name, This is also the default name of the package in Go. // I define Confession(Request) service Love {// I define Confession method RPC Confession(Request) returns (Response) {}} // Request message Request { string name = 1; } message Response {String result = 1; }

After the Protoc environment is installed, go to the proto file directory (e.g. Open)window git) Execute the following command to set theprotoCompile files topb.gofile

 protoc --go_out=plugins=grpc:. test.proto

Conversion results:

// Code generated by protoc-gen-go. DO NOT EDIT. // Versions: // Protoc-gen-go v1.25.0 // Protoc v3.13.0 // source: test.proto package test import ( context "context" proto "github.com/golang/protobuf/proto" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) // This is a compile-time assertion that a sufficiently up-to-date  version // of the legacy proto package is being used. const _ = proto.ProtoPackageIsVersion4 type Request struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } type Response struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Result string `protobuf:"bytes,1,opt,name=result,proto3" json:"result,omitempty"` } // LoveServer is the server API for Love service. type LoveServer interface { Confession(context.Context, *Request) (*Response, error) }

A DEMO

The directory structure is:


-------------------------------
| mygrpc
| ---------pb
| -------------test.proto
| ---------client.go
| ---------srv.go
-------------------------------

client.go

Package main import ("context" "log" "mygrpc.com/pb" "string") func main() {// Connect to GRPC server conn, err := grpc.Dial(":8888", grpc.WithInsecure()) if err ! = nil {log.fatal (err)} // defer conn.Close() // Initialize the client C := pB.newLoveClient (conn) // Initiate the request response, Err := c.onfession (context.background (), &pB.request {Name: "NeoZhen "}) if err! = nil { log.Fatal(err) } log.Println(response.Result) }

server.go

Package main import ("context" "log" "net" "google.golang.org/grpc" "key") // Implement Love service interface CONFESSION (L *Love) CONFESSION (CTX context.context, request * PB.request) (* PB.response, error) { resp := &pb.Response{} resp.Result = "your name is " + request.Name return resp, Nil} func main() {err := net.Listen(" TCP ", ":8888") if err! = nil {log.fatal (err)} // Instance GRPC Server S := GRPC.newServer () // RegisterLoveServer(S,) New (Love)) the Println (" Listen on 127.0.0.1:8888..." ) s.Serve(listen) }

Next time I’ll talk about GRPC certification

Technology is open, our mentality, should be open. Embrace change, live up to the sun, and strive to move forward.

I am Nezha, welcome thumb up to collect, see you next time