Google Protobuf结合Netty实践

1.Win版Protobuf代码生成工具下载:

https://github.com/protocolbuffers/protobuf/releases

注意下载protoc-3.6.1-win32.zip

2.编写.proto文件注意:

指定包为外层目录名称,指定java包名为你想使用的java工程该序列化类包名,还需要指定生成Java类的名称。示例:

syntax = "proto2";
package Protobuf;
option java_package = "com.xiaobai.codec.protobuf";
option java_outer_classname = "SubscribeReqProto";

message SubscribeReq{
required int32 subReqID = 1;
required string userName = 2;
required string productName = 3;
repeated string address = 4;
}

syntax = "proto2";
package Protobuf;
option java_package = "com.xiaobai.codec.protobuf";
option java_outer_classname = "SubscribeRespProto";

message SubscribeResp{
required int32 subReqID = 1;
required int32 respCode = 2;
required string desc = 3;
}

3.使用工具时需要注意

a.需要指定一个--proto_path路径,根据错误提示:

D:\protoc-3.6.1-win32\bin>protoc.exe --java_out=F:\NewAge\nettydemo\src\main\jav
a F:\NewAge\nettydemo\Protobuf\SubscribeReq.proto
F:\NewAge\nettydemo\Protobuf\SubscribeReq.proto: File does not reside within any
path specified using --proto_path (or -I). You must specify a --proto_path whi
ch encompasses this file. Note that the proto_path must be an exact prefix of t
he .proto file names -- protoc is too dumb to figure out when two paths (e.g. ab
solute and relative) are equivalent (it's harder than you think).

这个路径需要是.proto文件所在目录

b.需要在.proto文件中指定它的proto语法版本,这样生成时不会出现警告,根据提示,这个版本默认是proto2,可以设置为proto3:

D:\protoc-3.6.1-win32\bin>protoc.exe --proto_path=F:\NewAge\nettydemo\Protobuf -
-java_out=F:\NewAge\nettydemo\src\main\java F:\NewAge\nettydemo\Protobuf\Subscri
beReq.proto
[libprotobuf WARNING T:\src\github\protobuf\src\google\protobuf\compiler\parser.
cc:562] No syntax specified for the proto file: SubscribeReq.proto. Please use '
syntax = "proto2";' or 'syntax = "proto3";' to specify a syntax version. (Defaul
ted to proto2 syntax.)

参照:

https://www.jianshu.com/p/42a480a45cd6

https://www.cnblogs.com/gifisan/p/5976208.html?utm_source=itdadao&utm_medium=referral

生成效果如下:

Win版本安装参考与示例:

https://www.cnblogs.com/tyw66/p/7352033.html

Linux版本安装参考与示例:

https://www.cnblogs.com/learn21cn/p/6206206.html

https://www.cnblogs.com/luoxn28/p/5303517.html

猜你喜欢

转载自www.cnblogs.com/free-wings/p/10213055.html