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("xxxxxxx@126.com");

		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: "xxxxxxx@126.com"
  phone {
    number: "123456789012"
    type: HOME
  }
  phone {
    number: "7676767676767"
    type: MOBILE
  }
}

(将这段转化为纯字符串去掉换行和空格,需要占用128byte)

69(转化之后只需要69byte)



参考文档:

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值