preface

Hello, I’m Asong, and this is my seventh original article. Last article we use go standard library RPC practice, use is still very convenient, this article we will learn a GRPC.

1. gRPC

GRPC is a high-performance, universal open source RPC framework developed by Google. It is mainly developed for mobile applications and designed based on THE HTTP/2 Protocol standard. It is developed based on the Protocol Buffers (ProtoBuf) serialization Protocol and supports many development languages. His goal is to develop across languages and support multiple languages. In gRPC, a client application can call the methods of a server application on a different machine as directly as a local object, making it easier for you to create distributed applications and services.GRPC is based on the idea of defining a service and specifying methods (including parameters and return types) that can be called remotely. Implement this interface on the server side and run a gRPC server to handle the client calls. Having a stub on the client side can act like a server-side method. GRPC supports multiple languages, so we can use our favorite language to develop, the official website has related introduction.

2. protocol buffers

GRPC uses Protocol Buffers, a mature structured data serialization mechanism open-source by Google, by default, as well as other data formats, such as JSON. Protocol Buffers are now available in Proto3, with a lightweight simplified syntax, some useful new features, and support for multiple languages. Here is not introduced to use protocol buffers, detailed study click here: developers.google.com/protocol-bu…

3. GRPC practice

Language: Golang function: one user login interface, two servers, one Webserver for interaction with the front end, one tcpServer for processing login logic, two servers through RPC request call. Because this is mainly to demonstrate the use of gRPC, login logic does not operate the database, simply write a return example. First we write the proto file. Since it is the login interface, we can design the login request parameters and return parameters as follows:

syntax = "proto3"; package proto; option go_package = "proto/user.proto; user_proto"; //the request message containing the user's name password message LoginRequest { //user name string username = 1; //password string password = 2; } //the response message containing the user's information message LoginResponse { //user name string username = 1; string nickname = 2; //token string token = 3; //result code uint32 code = 4; //result msg string msg = 5; } service UserService { rpc login (LoginRequest) returns (LoginResponse){ } }Copy the code

The gRPC provides a code generation tool. Protoc-gen-go-grpc can be used to generate codes. The detailed operations are as follows:

$ export GO111MODULE=on  # Enable module mode
$ go get github.com/golang/protobuf/protoc-gen-go
Copy the code

After doing this, the executable will be generated in your GOPATH/bin directory by adding the path to the environment variable. Now you can use the protoc command for code generation, go to the project root directory, create a proto file, place the.proto file in this file, and execute the following command:

$protoc \ --go_out=Mgrpc/service_config/service_config.proto=/internal/proto/grpc_service_config:. \ --go-grpc_out=Mgrpc/service_config/service_config.proto=/internal/proto/grpc_service_config:. \ --go_opt=paths=source_relative \ --go-grpc_opt=paths=source_relative \ proto/user.proto
Copy the code

Then user_pb.go and user_grpc.pb.go are generated in the proto directory. Now that the protocol part is finished, I began to write the server and client part of the code as follows:

package main

import (
	"context"
	"log"
	"net"

	"google.golang.org/grpc"

	pb "asong.cloud/Golang_Dream/code_demo/grpc_demo/proto"
)

type Server struct {
	pb.UnimplementedUserServiceServer
}

func (s *Server)Login(ctx context.Context,in *pb.LoginRequest) (*pb.LoginResponse,error) {
	log.Printf("Received username: %s", in.Username)
	log.Printf("Received password: %s",in.Password)
	return &pb.LoginResponse{Username: in.Username,Nickname: "Golang Dream Factory",Token: "asong_grpc",Code: 0,Msg: "Successful landing."},nil
}

func main(a)  {
	lis, err := net.Listen("tcp".": 8080")
	iferr ! =nil{
		log.Fatalf("failed to listen :%v",err)
	}
	grpc := grpc.NewServer()
	pb.RegisterUserServiceServer(grpc, &Server{})
	iferr := grpc.Serve(lis); err ! =nil {
		log.Fatalf("failed to serve: %v", err)
	}
}

Copy the code
package main

import (
	"context"
	"log"
	"time"

	"google.golang.org/grpc"

	pb "asong.cloud/Golang_Dream/code_demo/grpc_demo/proto"
)

const (
	address = "localhost:8080"
)


func main(a)  {
	conn,err := grpc.Dial(address,grpc.WithInsecure(),grpc.WithBlock())
	iferr ! =nil{
		log.Fatalf("did not connect: %v",err)
	}

	defer conn.Close()
	c := pb.NewUserServiceClient(conn)

	ctx,cannel := context.WithTimeout(context.Background(),time.Second * 10)
	defer cannel()
	rsp ,err := c.Login(ctx,&pb.LoginRequest{Username: "asong",Password: "123"})
	iferr ! =nil{
		log.Fatalf("could not login request: %v",err)
	}
	log.Printf("Username: %s Code: %d Msg: %s", rsp.GetUsername(),rsp.Code,rsp.Msg)
}

Copy the code

Go run *. Go, the console will have the following output:

2020/07/30 22:12:37 Received username: asong
2020/07/30 22:12:37 Received password: 123

Copy the code

Webserver console output:

2020/07/30 22:12:37 Username: asong Code: 0 Msg: Login succeededCopy the code

4 summarizes

Well, that’s the end of this introduction. This is just a simple application, can be used as a start to watch, specific in-depth, or to see the official documentation, according to the project in-depth thinking. I am Asong, an ordinary struggling programmer. Welcome to pay attention to personal public number: Golang Dream Factory, regularly release go knowledge, you want to learn here!! To obtain the latest official Chinese document of GIN in 2020, please reply to the background of the official account: GIN.