东莞网站推广公司,wordpress警告函数未被定义,网站响应式建设,接单子做网站词上篇文章介绍了如何安装protobuf环境#xff0c;文章链接如下
【Go】protobuf介绍及安装-CSDN博客
本节介绍protobuf在gRPC中具体如何使用#xff0c;并编写测试用例
一、Protobuf是如何工作的 .proto文件是protobuf一个重要的文件#xff0c;它定义了需要序列化数据的结…上篇文章介绍了如何安装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文件
syntaxproto3;
option go_package./;student; //关于最后生成的go文件是处在哪个目录哪个包中.代表在当前目录生成student代表了生成的go文件的包名是studentservice DemoService {rpc Sender(StudentRequest) returns (StudentResponse){}
}message StudentRequest {string Id 1;
}message StudentResponse {string result 1;
}message Student {int64 Id 1; //idstring 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 mainimport (contextencoding/jsonerrorsgoogle.golang.org/grpcgoogle.golang.org/grpc/keepalivestudent goproject01/day34/grpc/protolognetstrconvtime
)// grpc生成源码后多了一个方法mustEmbedUnimplementedDemoServiceServer
// 这个方法首字母小写不允许重载自定义实现却没法实现该方法解决方法如下
/**
1生成代码时候使用选项
protoc --go_out. **--go-grpc_optrequire_unimplemented_serversfalse** --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.ServerOptionoptions append(options,grpc.KeepaliveParams(keepalive.ServerParameters{Time: 10 * time.Second, // wait time before ping if no activityTimeout: 20 * time.Second, // ping timeout}),grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{MinTime: 60 * time.Second, // min time a client should wait before sending a pingPermitWithoutStream: 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) //400kBoption3 : 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 byteslog.Println(返回客户端序列化字符串, string(bytes))return resp, nil
}4.编写客户端程序
package mainimport (contextflaggoogle.golang.org/grpcgoogle.golang.org/grpc/credentials/insecurestudent goproject01/day34/grpc/protologtime
)const (defaultName worlddefaultId 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文件为准。
syntaxproto3;
option go_package./;student; //关于最后生成的go文件是处在哪个目录哪个包中.代表在当前目录生成student代表了生成的go文件的包名是studentservice 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
1hellworld测试examples/helloworld
2route_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)