protobuf快速使用

2015-03-18  本文已影响0人  Angelo严

什么是protobuf

简单讲就是一种类似于json,xml的通用数据交换格式,但是效率更高,更省空间,目前官方支持c++,java,python,ruby。其他语言有一些第三方做的开发包,需要自己选择比较好的。

Ubuntu下快速使用

  1. 下载
    google或者github

  2. 编译
    2.1 编译protoc工具,这里可以直接看解压出来的protobuf-2.6.0文件夹下的README.txt文件,这里需要有c++编译器
    $ ./configure $ make $ make check $ make install
    2.2 测试安装
    $ protoc --version
    如果无法运行提示 error while loading shared libraries,我们可以直接把protoc默认安装的共享库文件路径直接加入到共享库配置文件中去(实际上很多开源软件的共享库文件默认安装的位置也在/usr/local/lib下)
    $ echo "/usr/local/lib" >> /etc/ld.so.conf $ ldconfig
    再执行一下应该就可以了
    $ protoc --version

  3. java使用示例
    3.1 把java源代码编译成我们方便使用的jar包形式,这里需要用到maven,没有的话可以在这里下载apache,安装说明这页上也有
    3.2 打包,先test一下
    $ mvn test
    通过了的话直接
    $ mvn package
    在target目录下就能看到打完包的protobuf-java-2.6.0.jar文件了
    3.3 用protoc工具将.proto文件生成java类
    这里直接用刚刚下载的protobuf-2.6.0中example文件夹下的addressbook.proto文件作为示例
    $ protoc -I=$SRC_DIR --java_out=$DST_DIR $SRC_DIR/addressbook.proto
    上面的$SRC_DIR表示存放addressbook.proto文件的路径,$DST_DIR表示生成java类存放的路径
    至此将protobuf-java-2.6.0.jar和刚刚生成的AddressBookProtos.java文件引用到你自己的项目中就可以了

  4. 使用
    4.1 写:AddPerson.java,为了方便直接在IDE里面使用,对官网程序做了一点修改,直接运行输入Person的相关信息就好了

     package com.example.tutorial;
    
     import java.io.BufferedReader;
     import java.io.FileInputStream;
     import java.io.FileNotFoundException;
     import java.io.FileOutputStream;
     import java.io.IOError;
     import java.io.IOException;
     import java.io.InputStreamReader;
     import java.io.PrintStream;
    
     import com.example.tutorial.AddressBookProtos.AddressBook;
     import com.example.tutorial.AddressBookProtos.Person;
    
     public class AddPerson {
    
         // This function fills in a Person message based on user input.
         static Person PromptForAddress(BufferedReader stdin, PrintStream stdout)
                 throws IOException {
             Person.Builder person = Person.newBuilder();
    
             stdout.print("Enter person ID: ");
             person.setId(Integer.parseInt(stdin.readLine()));
    
             stdout.print("Enter name: ");
             person.setName(stdin.readLine());
    
             stdout.print("Enter email address (blank for none)");
             String email = stdin.readLine();
             if (email.length() > 0) {
                 person.setEmail(email);
             }
    
             while (true) {
                 stdout.print("Enter a phone number (or leave blank to finish): ");
                 String number = stdin.readLine();
                 if (number.length() == 0) {
                     break;
                 }
    
                 Person.PhoneNumber.Builder phoneNumber = Person.PhoneNumber
                         .newBuilder().setNumber(number);
    
                 stdout.print("Is this a mobile, home, or work phone? ");
                 String type = stdin.readLine();
                 if (type.equals("mobile")) {
                     phoneNumber.setType(Person.PhoneType.MOBILE);
                 } else if (type.equals("home")) {
                     phoneNumber.setType(Person.PhoneType.HOME);
                 } else if (type.equals("work")) {
                     phoneNumber.setType(Person.PhoneType.WORK);
                 } else {
                     stdout.println("Unknown phone type.  Using default.");
                 }
    
                 person.addPhone(phoneNumber);
             }
    
             return person.build();
    
         }
    
         // Main function: Reads the entire address book from a file,
         // adds one person based on user input, then writes it back out to the same
         // file.
         public static void main(String[] args) throws Exception {
     //      if (args.length != 1) {
     //          System.err.println("Usage:  AddPerson ADDRESS_BOOK_FILE");
     //          System.exit(-1);
     //      }
     
             String filePath = "myPerson";
    
             AddressBook.Builder addressBook = AddressBook.newBuilder();
    
             // Read the existing address book.
             try {
                 addressBook.mergeFrom(new FileInputStream(filePath));
             } catch (FileNotFoundException e) {
                 System.out.println(filePath
                         + ": File not found.  Creating a new file.");
             }
    
             // Add an address.
             addressBook.addPerson(PromptForAddress(new BufferedReader(
                     new InputStreamReader(System.in)), System.out));
    
             // Write the new address book back to disk.
             FileOutputStream output = new FileOutputStream(filePath);
             addressBook.build().writeTo(output);
             output.close();
         }
    
     }
    

4.2 读:可以读取刚刚写在文件里的Person

    package com.example.tutorial;

    import java.io.FileInputStream;

    import com.example.tutorial.AddressBookProtos.AddressBook;
    import com.example.tutorial.AddressBookProtos.Person;

    public class ListPeople {

        // Iterates though all people in the AddressBook and prints info about them.
        static void Print(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());
                }
            }
        }

        // Main function: Reads the entire address book from a file and prints all
        // the information inside.
        public static void main(String[] args) throws Exception {
            String filePath = "myPerson";

            // Read the existing address book.
            AddressBook addressBook = AddressBook.parseFrom(new FileInputStream(filePath));

            Print(addressBook);
        }

    }
上一篇下一篇

猜你喜欢

热点阅读