1. 程式人生 > >Google Protobuf結合Netty實踐

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