QuickStart grpc-go framework

gRPC was developed by google, is a language-neutral, platform-neutral, open-source remote procedure call (RPC) system. gRPC default protocol buffers, this is a mature open source Google data structure serialization mechanism is said to be the industry's fastest serialization protocol.

And a GRPC grpc-go, because it is so remote communications need to be converted into a sequence of bytes, in the form of a binary sequence and then transmitted on the network. So we need to write a .proto file in the beginning, so protoc compiler generates .pb.go easy to use back.

hello.proto file
syntax = "proto3";          //指定语法版本
package helloword;          //指定生成后的 hello.pb.go 的包名

//一个 RPC 服务通过参数和返回类型来指定可以远程调用的方法
service Hello {
    // rpc 定义可远程调用服务
    rpc HelloWorld (HelloRequest) returns (HelloReply) {}
}

//消息定义的关键字,相当于struct
message HelloRequest {
    // [修饰符] 类型 字段名 = 标识符;
    //标识符是用来在二进制格式中识别各个字段的,可以简单理解为序列化后的二进制数据中的布局位置顺序
    string name = 1;
}

message HelloReply {
    string message = 1;
}

In the terminal, type protoc -I . --go_out=plugins=grpc:. ./hello.proto
Here Insert Picture Description
on the command line:
-I: Specifies the search path for the import file
--go_out=: Specifies the path of the generated file, where specified in the current path generated
plugins=grpc: grpc plugin with the Command to execute this Protoc
./hello.proto: designated to be compiled proto file

We can see automatically generates a path in the current .pb.goformat file
Here Insert Picture Description

Due to the generation of hello.pb.gomore content, not covered here, let's start to achieve service and client
Here Insert Picture Description

Implement server-side

package main
import (
	"google.golang.org/grpc"
	pb "helloworld"
	"net"
	"log"
	"context"
)

//用于实现HelloServer
type server struct{}

//服务实现
func (s *server) HelloWorld(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
	log.Printf("Received: %v", in.Name)
	return &pb.HelloReply{Message: "Hello " + in.Name}, nil
}

func main() {
	//监听
	list, err := net.Listen("tcp", ":9999")
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}

	//
	ser := grpc.NewServer()

	//注册到grpc
	pb.RegisterHelloServer(ser, &server{})

	//读取请求并响应
	err = ser.Serve(list)
	if err != nil {
		log.Fatalf("failed to serve: %v", err)
	}
}

The server can see there are two main work is to realize we were in a hello.protoservice interface definition service Hello, to implement this interface must implement all the methods it contains, and the other is to build grpc server from the client to listen client requests and responses

Client implementation

package main

import (
	pb "helloworld"
	"google.golang.org/grpc"
	"log"
	"os"
	"time"
	"context"
)

func main() {
	//连接服务端句柄
	//WithInsecure()不指定安全选项
	conn, err := grpc.Dial("localhost:9999", grpc.WithInsecure())
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()

	cli := pb.NewHelloClient(conn)

	name := "World"
	//获取命令行参数
	if len(os.Args) > 1 {
		name = os.Args[1]
	}

	//设置上下文超时
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()

	//响应
	resp, err := cli.HelloWorld(ctx, &pb.HelloRequest{Name: name})
	if err != nil {
		log.Fatalf("could not succ: %v", err)
	}
	log.Printf("Receive from server: %s", resp.Message)
}

The client implementation routines that are basically like, where the security option is an authorization and authentication (eg, TLS, GCE certification, JWT certification)

run

go run server/main.go
Here Insert Picture Description

go run client/main.go
Here Insert Picture Description

Reference
https://github.com/grpc/grpc-go/tree/master/examples/helloworld
http://doc.oschina.net/grpc?t=56831

Published 22 original articles · won praise 6 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_42403866/article/details/88851602