篇文章介绍如何安装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的clientserver)
	/**
	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 = &amp;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 := &amp;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 := &amp;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:%vn", err)
	}
	defer connection.Close()

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

	resp, errs := client.Sender(ctx, &amp;student.StudentRequest{Id: *id})
	if errs != nil {
		log.Fatalf("client call server Sender method fail:%vn", 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)

原文地址:https://blog.csdn.net/smallbirdnq/article/details/134741496

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_43820.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注