[TOC]

gRPC

GRPC introduction

What is gRPC?

What is the difference between RPC and RESTful?

RPC message transport can be TCP, UDP, or HTTP. When RPC message transport is HTTP, its structure is similar to RESTful architecture

What’s the difference between RPC and RESTful:

  • The function is more flexible if the operation object is different

RPC operates on method objects and RESTful operates on resources

The client and server of RPC are tightly coupled, and the client needs to know the function name, parameter type and order of the server to make remote procedure call.

RESTful Indicates HTTP – based semantic operation resources. Parameter order is generally independent

  • RCP is more suitable for customization

    RESTful operations are performed on resources and are mainly CURD operations. If a specific function, such as calculating the average score of a class, is needed, it makes more sense to use RPC to define server methods (such as Stu.CalAvg) for the client to call

What are the features of gRPC?

  • GRPC can be developed across languages

GRPC clients can directly call remote programs on different servers, using gestures that look like local procedure calls, making it easy to build distributed applications and services. The client and server can be implemented using different languages supported by gRPC.

  • Designed based on the HTTP2 standard, it has some advantages over other frameworks
    • supportLong connection, bidirectional flow, header compression, multiplexing requestsEtc.
    • Save bandwidth,The number of TCP connections is reduced,Save CPU usageandExtend battery life
    • Improves the performance of cloud services and Web applications
    • Client and server interactions are transparent
    • GRPC uses Protobuf to serialize data by default

What is the data interaction mode of gRPC?

Request response

The client issues a request that reads 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 clients and servers can send a series of messages by reading and writing data streams

Method of data serialization – Protobuf

Protobuf is a way of serializing data, similar to JSON, XML, etc

A brief introduction to the three keywords in a Protobuf structure definition

  • Statements with the suffix. Proto end with a semicolon except for structure definitions
  • The structure definition can contain three keywords: message, service, and enum
  • Semicolons at the end of RPC method definitions are optional

The Message name is humped and the field is lowercase and underlined

 message ServerRequest {
      required string my_name = 1;
  }
Copy the code

The name of the Enums type is humped, and the name of the field is uppercase letters and underscores

 enum MyNum {
      VALUE1 = 1;
      VALUE2 = 2;
  }
Copy the code

The Service and RPC methods are named in camel shape

service Love {
  // Define the Confession method
  rpc MyConfession(Request) returns (Response) {}}Copy the code

For details on how to install prtobuf, see the 5 steps to install PROTOBUF.

The proto file uses the package keyword to declare the package name. By default, the package name in go is the same as this. You can customize the package name by changing go_package:

test.proto

syntax = "proto3"; / / proto versions

package pb; // Specify the package name, which is the default package name in go

// Define the Love service
service Love {
  // Define the Confession method
  rpc Confession(Request) returns (Response) {}}/ / request
message Request {
  string name = 1;
}

/ / response
message Response {
  string result = 1;
}
Copy the code

Once the protoc environment is installed, go to the directory of the proto file (e.gwindow git) Run the following command to change theprotoFile compiled intopb.gofile

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

Conversion result:

// 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)
}

Copy the code

A DEMO

The directory structure is:


-------------------------------
| mygrpc
| ---------pb
| -------------test.proto
| ---------client.go
| ---------srv.go
-------------------------------
Copy the code

client.go

package main

import (
    "context"
    "log"

    "mygrpc.com/pb"

    "google.golang.org/grpc"
)

func main(a) {
    // Connect to GRPC service
    conn, err := grpc.Dial(": 8888", grpc.WithInsecure())
    iferr ! =nil {
        log.Fatal(err)
    }
    / / is very critical
    defer conn.Close()

    // Initialize the client
    c := pb.NewLoveClient(conn)

    // Initiate a request
    response, err := c.Confession(context.Background(), &pb.Request{Name: Nezha})
    iferr ! =nil {
        log.Fatal(err)
    }

    log.Println(response.Result)
}
Copy the code

server.go

package main

import (
    "context"
    "log"
    "net"

    "google.golang.org/grpc"
    "mygrpc.com/pb"
)

// Define the Love service
type Love struct{}// Implement the Love service interface
func (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(a) {
    // Listen on port 8888
    listen, err := net.Listen("tcp".": 8888")
    iferr ! =nil {
        log.Fatal(err)
    }

    // Instantiate GRPC Server
    s := grpc.NewServer()

    // Register for the Love service
    pb.RegisterLoveServer(s, new(Love))

    log.Println("Listen on 127.0.0.1:8888...")
    s.Serve(listen)
}
Copy the code

Next time about gRPC certification

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

I am Nezha, welcome to like, see you next time ~