tonglin0325的个人主页

Ubuntu16.04安装protobuf

1.proto2#

1.protobuf的github地址

1
2
https://github.com/protocolbuffers/protobuf

去releases下载需要的版本

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

选择2.5.0的版本

1
2
https://github.com/protocolbuffers/protobuf/releases/tag/v2.5.0

下载

1
2
wget https://github.com/protocolbuffers/protobuf/releases/download/v2.5.0/protobuf-2.5.0.tar.gz

编译安装

1
2
3
4
5
6
./autogen.sh
./configure
make
make check
sudo make install

安装完毕,查看版本

1
2
3
protoc --version
libprotoc 2.5.0

参考google的javatutorial

1
2
https://developers.google.com/protocol-buffers/docs/javatutorial

pb的数据类型如下

1
2
https://developers.google.com/protocol-buffers/docs/proto

 

 

 

下载文件addressbook.proto

1
2
https://github.com/protocolbuffers/protobuf/blob/v2.5.0/examples/addressbook.proto

 编译成java代码

1
2
3
4
protoc -I=./ --java_out=./ ./addressbook.proto # protoc -I=$SRC_DIR --java_out=$DST_DIR $SRC_DIR/addressbook.proto
或者
protoc --java_out=. addressbook.proto

生成文件

1
2
3
4
5
6
7
8
tree -L 4
.
├── addressbook.proto
└── com
└── example
└── tutorial
└── AddressBookProtos.java

2.proto3#

如果想使用proto3的话,需要添加如下语法,否则编译器会使用proto2

1
2
syntax = "proto3";

参考

1
2
https://github.com/protocolbuffers/protobuf/blob/main/examples/addressbook.proto

以及

1
2
https://docs.confluent.io/platform/current/schema-registry/fundamentals/serdes-develop/serdes-protobuf.html

3.proto定义#

1
2
3
4
5
6
message HelloRequest {
string name = 1; // 转换为json的时候,"name": ""
optional string name1 = 2; // 转换为json的时候,将没有key
google.protobuf.StringValue name2 = 3; // 转换为json的时候,"name2": null
}