【GO】protobuf在golang中的测试用例

上篇文章介绍了如何安装protobuf环境,文章链接如下

【Go】protobuf介绍及安装-CSDN博客

本节介绍protobuf在gRPC中具体如何使用,并编写测试用例

一、Protobuf是如何工作的

  .proto文件是protobuf一个重要的文件,它定义了需要序列化数据的结构,当protobuf编译器(protoc)来运行.proto文件时候,编译器将生成所选择的语言的代码,比如你选择go语言,那么就会将.proto转换成对应的go语言代码,对于go来说,编译器会为每个消息类型生成一个pd.go文件,而C++会生成一个.h文件和一个.cc文件。

  使用protobuf的3个步骤是:

    1. 在.proto文件中定义消息格式。

    2. 用protobuf编译器编译.proto文件。

    3. 用C++/Java/go等对应的protobuf API来写或者读消息。

二、Protobuf代码测试

在开始代码编写与测试之前,把官网的链接分享给大家,这个看完可以避坑,尤其是版本,示例代码,proto文件格式等。

工具安装及demo测试:Quick start | Go | gRPC

1.定义proto文件

syntax="proto3";
option go_package="./;student"; //关于最后生成的go文件是处在哪个目录哪个包中,.代表在当前目录生成,student代表了生成的go文件的包名是student

service DemoService {
  rpc Sender(StudentRequest) returns (StudentResponse){}
}

message StudentRequest {
  string Id = 1;
}

message StudentResponse {
  string result =1;
}

message Student {
  int64 Id = 1; //id
  string Name =2; //姓名
  string No =3; //学号
}

2.生成代码

进入proto文件所在目录,cd ~/sourceCode/go/goproject01/src/day34/grpc/proto

<1>执行protoc --go_out=. student.proto

protoc --go_out=. student.proto

执行后发现proto目录生成了一个文件:student.pb.go

<2>执行protoc --go-grpc_out=. student.proto,发现命令执行报错如下

cd ~/sourceCode/go/goproject01/src/day34/grpc/proto
protoc --go-grpc_out=. student.proto 
protoc-gen-go-grpc: program not found or is not executable
Please specify a program using absolute path or make sure the program is available in your PATH system variable
--go-grpc_out: protoc-gen-go-grpc: Plugin failed with status code 1.

执行报错,发现没有安装protoc-gen-go-grpc,需要安装一下

先执行go get

go get google.golang.org/grpc/cmd/protoc-gen-go-grpc
go: downloading google.golang.org/grpc v1.59.0
go: downloading google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.3.0
go: downloading google.golang.org/protobuf v1.28.1
go: added google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.3.0
go: added google.golang.org/protobuf v1.28.1

再执行go install

go install google.golang.org/grpc/cmd/protoc-gen-go-grpc

执行完在$GOBIN目录下生成protoc-gen-go-grpc,源码对应在pkg下

再次执行protoc --go-grpc_out=. student.proto

protoc --go-grpc_out=. student.proto

执行后会在当前目录生成一文件:student_grpc.pb.go

<3>执行go mod tidy

打开文件发现依赖的包没有导入,会报错,需要执行一下最小化导入包依赖

go mod tidy
go: finding module for package google.golang.org/grpc
go: finding module for package google.golang.org/grpc/status
go: finding module for package google.golang.org/grpc/codes
go: found google.golang.org/grpc in google.golang.org/grpc v1.59.0
go: found google.golang.org/grpc/codes in google.golang.org/grpc v1.59.0
go: found google.golang.org/grpc/status in google.golang.org/grpc v1.59.0
go: downloading google.golang.org/genproto v0.0.0-20230822172742-b8732ec3820d
go: downloading golang.org/x/text v0.12.0

执行后生成的代码编译通过,不再报错。

3.编写Server端程序

在server包下创建server.go文件

package main

import (
	"context"
	"encoding/json"
	"errors"
	"google.golang.org/grpc"
	"google.golang.org/grpc/keepalive"
	student "goproject01/day34/grpc/proto"
	"log"
	"net"
	"strconv"
	"time"
)

// grpc生成源码后多了一个方法mustEmbedUnimplementedDemoServiceServer
// 这个方法首字母小写不允许重载,自定义实现却没法实现该方法,解决方法如下
/**
1,生成代码时候使用选项:
protoc --go_out=. **--go-grpc_opt=require_unimplemented_servers=false** --go-grpc_out=. proto/*.proto
This works, but your binary will fail to compile if you add methods to your service(s) and regenerate/recompile.
That is why we have the embedding requirement by default. We recommend against using this option.
We recommend against using this option(不推荐使用此选项)

2,使用内嵌的结构体定义
// server is used to implement helloworld.GreeterServer.
type server struct{
// Embed the unimplemented server
helloworld.UnimplementedGreeterServer
}

*/
type MyDemeServiceImpl struct {
	student.UnimplementedDemoServiceServer
}

func (ds *MyDemeServiceImpl) Sender(ctx context.Context, in *student.StudentRequest) (*student.StudentResponse, error) {
	return handSendMessage(ctx, in)
}

func main() {
	//绑定9091端口
	listener, err := net.Listen("tcp", ":10005")
	if err != nil {
		log.Fatalf("bingding port:9091 error:%v", err)
	}

	//注册服务
	//这个连接最大的空闲时间,超过就释放,解决proxy等到网络问题(不通知grpc的client和server)
	/**
	func NewGrpcServer(opts ...grpc.ServerOption) *grpc.Server {
		var options []grpc.ServerOption
		options = append(options,
			grpc.KeepaliveParams(keepalive.ServerParameters{
				Time:    10 * time.Second, // wait time before ping if no activity
				Timeout: 20 * time.Second, // ping timeout
			}),
			grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{
				MinTime:             60 * time.Second, // min time a client should wait before sending a ping
				PermitWithoutStream: true,
			}),
			grpc.MaxRecvMsgSize(Max_Message_Size),
			grpc.MaxSendMsgSize(Max_Message_Size),
		)
		for _, opt := range opts {
			if opt != nil {
				options = append(options, opt)
			}
		}
		return grpc.NewServer(options...)
	}
	*/
	option1 := grpc.KeepaliveParams(keepalive.ServerParameters{MaxConnectionIdle: 5 * time.Minute})
	option2 := grpc.MaxSendMsgSize(409600) //400kB
	option3 := grpc.MaxRecvMsgSize(409600)
	grpcServer := grpc.NewServer(option1, option2, option3)
	//impliServer := student.UnimplementedDemoServiceServer{}
	var impliServer = &MyDemeServiceImpl{}
	student.RegisterDemoServiceServer(grpcServer, impliServer)
	log.Printf("server listening at %v", listener.Addr())
	/*
		错误的写成http了,导致排查半天
		err = http.Serve(listener, nil)
			if err != nil {
				log.Fatalf("http serve fail:%v", err)
			}*/
	if err := grpcServer.Serve(listener); err != nil {
		panic("error building server: " + err.Error())
	}
}

func handSendMessage(ctx context.Context, req *student.StudentRequest) (*student.StudentResponse, error) {
	log.Println("receive param=", req.GetId())
	//模拟根据id查询student对象并构建一个student实例
	sid := req.GetId()
	if sid == "" {
		log.Println("request param id is null")
		return nil, errors.New("request param id is null")
	}
	resp := &student.StudentResponse{}
	sidInt64, err := strconv.ParseInt(sid, 10, 64)
	if err != nil {
		log.Printf("sid:%s covert to int64 error", sid)
		return nil, errors.New("sid covert to int64 error")
	}
	//通过proto进行序列化对象,和原始json以及easyJson使用方法类似
	s := &student.Student{Name: "xiaoliu", No: "10001", Id: sidInt64}

	//bytes, errs := proto.Marshal(s) //需要一个指针类型对象
	bytes, errs := json.Marshal(s)
	if errs != nil {
		log.Println("student obj convert to json error")
		return nil, errors.New("student obj convert to json error")
	}
	resp.Result = bytes
	log.Println("返回客户端序列化字符串:", string(bytes))
	return resp, nil
}

4.编写客户端程序

package main

import (
	"context"
	"flag"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	student "goproject01/day34/grpc/proto"
	"log"
	"time"
)

const (
	defaultName = "world"
	defaultId   = "10001"
)

var (
	address = flag.String("address", "localhost:10005", "the address connect to ")
	name    = flag.String("name", defaultName, " name to great")
	id      = flag.String("id", defaultId, "id send to server")
)

func main() {

	flag.Parse()
	connection, err := grpc.Dial(*address, grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("connect localhost:9091 fail:%v\n", err)
	}
	defer connection.Close()

	client := student.NewDemoServiceClient(connection)
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
	defer cancel()

	resp, errs := client.Sender(ctx, &student.StudentRequest{Id: *id})
	if errs != nil {
		log.Fatalf("client call server Sender method fail:%v\n", errs)
	}
	//获取StudentResponse result的内容
	rst := string(resp.GetResult())
	log.Println("rpc returns result:", rst)

}

5.代码测试

<1>启动服务端程序

go run server.go
//启动后打开服务端端口,等待客户端连接日志
2023/12/04 18:24:17 server listening at [::]:10005

//启动后接收客户端的参数打印
2023/12/04 18:24:25 receive param= 10001
2023/12/04 18:24:25 返回客户端序列化字符串: {"Id":10001,"Name":"xiaoliu","No":"10001"}

<2>运行客户端程序

go run client.go

首次执行发现报错如下:

rpc error: code = Unavailable desc = connection error: desc = "error reading server preface: http2: frame too large"

错误解决:自己误把grpc协议写为http,修改代码即可:

/*
		错误的写成http了,导致排查半天
		err = http.Serve(listener, nil)
			if err != nil {
				log.Fatalf("http serve fail:%v", err)
			}*/
	if err := grpcServer.Serve(listener); err != nil {
		panic("error building server: " + err.Error())
	}

再次执行报错如下:

2023/12/04 18:09:55 client call server Sender method fail:rpc error: code = Internal desc = grpc: error while marshaling: string field contains invalid UTF-8
错误解决:需要修改student.proto文件中StudentResponse的result字段为bytes类型,用来支持utf-8字符。将student.proto文件修改如下:上面的server.go,client.go最终以这个proto文件为准。

syntax="proto3";
option go_package="./;student"; //关于最后生成的go文件是处在哪个目录哪个包中,.代表在当前目录生成,student代表了生成的go文件的包名是student

service DemoService {
  rpc Sender(StudentRequest) returns (StudentResponse){}
}

message StudentRequest {
  string Id = 1;
}

message StudentResponse {
  bytes result =1; //涉及到utf-8编码的字符需要使用bytes类型
}

message Student {
  int64 Id = 1; 
  string Name =2;
  string No =3;
}

修改后运行客户端程序:

调用服务端获取序列化的结果如下

go run client.go
2023/12/04 18:24:25 rpc returns result: {"Id":10001,"Name":"xiaoliu","No":"10001"}

6. gRPC官网文档

这里go官网提供使用gRPC开发步骤

Quick start | Go | gRPC

Basics tutorial | Go | gRPC

<1>hellworld测试:examples/helloworld

<2>route_guide测试:examples/route_guide

以上两个测试程序官网都有对应的文档,按照步骤测试执行即可。

7. 补充protobuf定义的数据类型

####

参考资料

gRPC介绍:​​​​​​Basics tutorial | Go | gRPC

Server到Client数据发送过程解析:gRPC 源码分析(四): gRPC server 中 frame 的处理 - 掘金

使用go实现gRPC:墨滴社区

HTTP/2:RFC7540:RFC 7540/7541: Hypertext Transfer Protocol Version 2 (HTTP/2)

相关推荐

  1. 如何seata编写测试

    2023-12-05 15:38:06       12 阅读
  2. 软件测试测试

    2023-12-05 15:38:06       19 阅读
  3. 测试设计思路

    2023-12-05 15:38:06       34 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-05 15:38:06       14 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-05 15:38:06       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-05 15:38:06       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-05 15:38:06       18 阅读

热门阅读

  1. Spark_spark shell退出方式

    2023-12-05 15:38:06       34 阅读
  2. golang实现文件上传(高并发+分块+断点续传+加密)

    2023-12-05 15:38:06       40 阅读
  3. 131. 分割回文串

    2023-12-05 15:38:06       33 阅读
  4. Hadoop

    2023-12-05 15:38:06       24 阅读
  5. Hadoop

    2023-12-05 15:38:06       30 阅读