Protobuf简单安装使用(Java)

一、protobuf安装 (ubuntu 条件下)

$ sudo su
$ sudo apt-get install autoconf automake libtool curl
$ git clone https://github.com/google/protobuf
$ cd protobuf
$ ./autogen
$ ./configure --prefix=/usr
$ make
$ make check
$ sudo make install
$ sudo ldconfig 

(./configure --prefix 会把protobuf安装到对应目录下,可以先建好文件夹避免内容混乱)


二、安装后续

sudo vim /etc/profile
 添加
export PATH=$PATH:/usr/bin/     (路径根据上面configure --prefix 来确定)
export PKG_CONFIG_PATH=/usr/lib/pkgconfig/
保存执行
source /etc/profile

同时 在~/.profile中添加上面两行代码,否则会出现登录用户找不到protoc命令

3 > 配置动态链接库路径
sudo vim /etc/ld.so.conf
插入:

/usr/lib

(以上路径都要根据之前安装的路径来写)

4 > sudo ldconfig

三、使用

maven项目

在pom.xml中添加如下依赖

 com.google.protobuf
 protobuf-java
 3.5.1

proto文件

 Protobuf消息定义
消息由至少一个字段组合而成,类似于C语言中的结构。每个字段都有一定的格式。
字段格式:限定修饰符① | 数据类型② | 字段名称③ | = | 字段编码值④ | [字段默认值⑤]

.proto类型                         Java 类型
double                                 double
float                                        float
sint32                                      int
sint64                                     long
bool                                      boolean
string                                      String

限定修饰符包含 {
    required: 必填字段
    optional: 可选字段
    repeated:数组集合字段

}

写一个test.proto文件,放到项目目录

syntax="proto2";
package tutorial;

option java_package = "com.czw.model";
option java_outer_classname = "AddressBookProtos";

message Person {
  required string name = 1;
  required int32 id = 2;
  optional string email = 3;

  enum PhoneType {
    MOBILE = 0;
    HOME = 1;
    WORK = 2;
  }

  message PhoneNumber {
    required string number = 1;
    optional PhoneType type = 2 [default = HOME];
  }

  repeated PhoneNumber phone = 4;
}

message AddressBook {
  repeated Person person = 1;
}
然后切换到项目的src/main/java目录   命令框输入

protoc --java_out=./  test.proto

即可生成对应的AddressBookProtos.java 文件


测试

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import com.czw.model.AddressBookProtos;
import com.czw.model.AddressBookProtos.*;

public class test1 {
    public static void main(String[] args) throws IOException{
        test1 demo=new test1();
        demo.serialize();
        System.out.println("serialize to disk success!!");
        System.out.println("start deserialize......");
        demo.deserialize();


    }

    public static void Print(AddressBookProtos.AddressBook addressBook) {
        for (Person person: addressBook.getPersonList()) {
            System.out.println("Person ID: " + person.getId());
            System.out.println("  Name: " + person.getName());
            if (person.hasEmail()) {
                System.out.println("  E-mail address: " + person.getEmail());
            }

            for (Person.PhoneNumber phoneNumber : person.getPhoneList()) {
                switch (phoneNumber.getType()) {
                    case MOBILE:
                        System.out.print("  Mobile phone #: ");
                        break;
                    case HOME:
                        System.out.print("  Home phone #: ");
                        break;
                    case WORK:
                        System.out.print("  Work phone #: ");
                        break;
                }
                System.out.println(phoneNumber.getNumber());
            }
        }
    }

    public void serialize() throws IOException {
        //build message
        Person john =
                Person.newBuilder()
                        .setId(3330)
                        .setName("Barry")
                        .setEmail("[email protected]")
                        .addPhone(
                                Person.PhoneNumber.newBuilder()
                                        .setNumber("123-4567")
                                        .setType(Person.PhoneType.HOME))
                        .build();

        AddressBook.Builder addressBook = AddressBook.newBuilder();
        addressBook.addPerson(john);

        //serialize to disk
        FileOutputStream output = new FileOutputStream("addressbook.pbd");
        addressBook.build().writeTo(output);
        output.close();
    }
    public void deserialize() throws FileNotFoundException, IOException{
        AddressBook addressBook =
                AddressBook.parseFrom(new FileInputStream("addressbook.pbd"));
        Print(addressBook);
    }

}


你可能感兴趣的:(Java)