Protocol Buffer實戰

一、Protocol buffers 是什麼

一套靈活、高效、自動化的結構化數據序列化開發工具包,比XML更加 小、快速、簡單,支持Java、C++、Python等多種語言。

Protocol buffers are a flexible, efficient, automated mechanism for serializing structured data – think XML, but smaller, faster, and simpler. You define how you want your data to be structured once, then you can use special generated source code to easily write and read your structured data to and from a variety of data streams and using a variety of languages. You can even update your data structure without breaking deployed programs that are compiled against the "old" format.



二、Protocol buffers 優勢在哪裏
language-neutral(跨語言)、 platform-neutral(跨平臺) 、extensible(可擴展)

language-neutral, platform-neutral, extensible way of serializing structured data for use in communications protocols, data storage, and more.


相對於XML優勢在於以下: 
更簡單 (simpler)
壓縮率更高 3 to 10 times smaller
速度更快 20 to 100 times faster
are less ambiguous
generate data access classes that are easier to use programmatically



三、實戰
1、下載

protobuf-java-2.4.1.jar,下載地址 http://grepcode.com/snapshot/repo1.maven.org/maven2/com.google.protobuf/protobuf-java/2.4.1

protoc-2.4.1-win32.zip,下載地址 https://code.google.com/p/protobuf/downloads/list


2、編寫.proto文件

文件名:addressbook.proto

// See README.txt for information and build instructions.
package tutorial;


option java_package = "edu.ruc.gis";
option java_outer_classname = "AddressBookProtos";

message Person {
  required string name = 1;
  required int32 id = 2;        // Unique ID number for this person.
  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;
}

// Our address book file is just one of these.
message AddressBook {
  repeated Person person = 1;
}


2、編譯proto文件

解壓protoc-2.4.1-win32.zip得到protoc.exe文件,將.proto文件和protoc.exe放在一起,

在當前目錄命令行執行 protoc --java_out=./ addressbook.proto



編譯生成Java文件



3、構建Java Project

在Eclipse中構建項目,引入protobuf-java-2.4.1.jar並加入Build path, 將上一步生成的 AddressBookProtos.java文件複製到src中。項目結構如下圖:



編寫測試類Main.java

package xxx.xxx.xxx;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import xxx.xxx.xxx.AddressBookProtos.AddressBook;
import xxx.xxx.xxx.AddressBookProtos.Person;
import xxx.xxx.xxx.AddressBookProtos.Person.PhoneNumber;
import xxx.xxx.xxx.AddressBookProtos.Person.PhoneType;

public class Main {

	public static void main(String[] args) {
		// testBuildAddressBook();
		// testReadAddressBook();
	}

	static void testBuildAddressBook() {
		AddressBook.Builder bookBuilder = AddressBook.newBuilder();
		Person.Builder pb = Person.newBuilder();
		pb.setId(23);
		pb.setName("Test Name");
		pb.setEmail("[email protected]");

		PhoneNumber.Builder pnb = PhoneNumber.newBuilder();
		pnb.setNumber("123456789012");
		pnb.setType(PhoneType.HOME);
		pb.addPhone(pnb.build());

		pnb = PhoneNumber.newBuilder();
		pnb.setNumber("7676767676767");
		pnb.setType(PhoneType.MOBILE);
		pb.addPhone(pnb.build());

		bookBuilder.addPerson(pb.build());

		AddressBook book = bookBuilder.build();
		try (FileOutputStream fsout = new FileOutputStream(new File("book.txt"))) {
			book.writeTo(fsout);
		} catch (Exception e) {
		}

		System.out.println(book.toString());
		System.out.println();
		System.out.println(book.toByteArray().length);

	}

	static void testReadAddressBook() {
		AddressBook book = null;
		try (FileInputStream fsin = new FileInputStream(new File("book.txt"))) {
			book = AddressBook.parseFrom(fsin);
		} catch (Exception e) {
			book = null;
		}
		if (book != null) {
			System.out.println(book.toString());
			System.out.println();
			System.out.println(book.toByteArray().length);
		}

	}

}


4、測試結果

取消main中的註釋可以執行相應的測試程序

執行 testBuildAddressBook

輸出爲:

person {
  name: "Test Name"
  id: 23
  email: "[email protected]"
  phone {
    number: "123456789012"
    type: HOME
  }
  phone {
    number: "7676767676767"
    type: MOBILE
  }
}

(將這段轉化爲純字符串去掉換行和空格,需要佔用128byte)

69(轉化之後只需要69byte)



參考文檔:

https://developers.google.com/protocol-buffers/docs/overview



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章