测试环境:Ubuntu 16.04 LTS
-
到protobuf的release页面
下载源码:https://github.com/protocolbuffers/protobuf/releases/download/v3.6.1/protobuf-all-3.6.1.tar.gz -
安装编译依赖
sudo apt-get install autoconf automake libtool curl make g++ unzip
-
解压、编译、安装(测试时是非root帐号,所以install时需要sudo)
tar -xvf protobuf-all-3.6.1.tar.gz cd protobuf-3.6.1 ./configure --prefix=/usr/local/protobuf make make check sudo make install
-
配置1:环境变量(参考链接)
vim /etc/profile 添加两行: export PATH=$PATH:/usr/local/protobuf/bin/ export PKG_CONFIG_PATH=/usr/local/protobuf/lib/pkgconfig/ source /etc/profile ~/.profile中也添加上面两行
-
配置2:动态链接库
cd /etc/ld.so.conf.d/ sudo vi protobuf.conf 添加一行: /usr/local/protobuf/lib ldconfig
-
确认版本
$ protoc --version libprotoc 3.6.1
-
验证(转自)
vi message.protosyntax = "proto3"; message Person { int32 id = 1; string name = 2; repeated Phone phone = 4; enum PhoneType { MOBILE = 0; HOME = 1; WORK = 2; } message Phone { string number = 1; PhoneType type = 2; } }
protoc --java_out=./java ./proto/message.proto
-
java代码验证
maven引入:<dependency> <groupId>com.google.protobuf</groupId> <artifactId>protobuf-java-util</artifactId> <version>3.6.1</version> </dependency>
gradle引入:
compile 'com.google.protobuf:protobuf-java:3.6.1'
java代码
import com.google.protobuf.InvalidProtocolBufferException; import java.util.Arrays; import java.util.List; public class App { public static void main(String[] args) { Message.Person.Builder personBuilder = Message.Person.newBuilder(); personBuilder.setId(12345678); personBuilder.setName("Admin"); personBuilder.addPhone(Message.Person.Phone.newBuilder().setNumber("10010").setType(Message.Person.PhoneType.MOBILE)); personBuilder.addPhone(Message.Person.Phone.newBuilder().setNumber("10086").setType(Message.Person.PhoneType.HOME)); personBuilder.addPhone(Message.Person.Phone.newBuilder().setNumber("10000").setType(Message.Person.PhoneType.WORK)); Message.Person person = personBuilder.build(); byte[] buff = person.toByteArray(); try { Message.Person personOut = Message.Person.parseFrom(buff); System.out.printf("Id:%d, Name:%s ", personOut.getId(), personOut.getName()); List<Message.Person.Phone> phoneList = personOut.getPhoneList(); for (Message.Person.Phone phone : phoneList) { System.out.printf("PhoneNumber:%s (%s) ", phone.getNumber(), phone.getType()); } } catch (InvalidProtocolBufferException e) { e.printStackTrace(); } System.out.println(Arrays.toString(buff)); } }
其他