protobuf介绍


按照官网的描述:protobuf是google提供的一个开源序列化框架。主要 应用于通信协议,数据存储中的结构化数据的序列化。它类 似于XML,JSON这样的数据表示语言,其最大的特点是基于二进制,因此比传统的XML表示高效短小得多。虽然是二进制数据格式,但并没有因此变得复 杂,开发人员通过按照一定的语法定义结构化的消息格式,然后送给命令行工具,工具将自动生成相关的类,可以支持java、c++、Python等语言环 境。通过将这些类包含在项目中,可以很轻松的调用相关方法来完成业务消息的序列化与反序列化工作。



protobuf的优势


1、语言中立

2、平台中立

3、高效性


protobuf入门(eclipse下java环境的搭建)


更多案例请查阅源代码包protobuf-2.3.0.zip  里面有关于各种支持语言(java,C++,python等 )的案例。

1、下载jar包 protobuf-java-2.3.0.jar

2、下载编译器protoc.exe

3、新建java工程test_protobuf

4、导入protobuf-java-2.3.0.jar包

5、导入编译器protoc.exe到项目下

6、在项目下建存放文件.proto的文件夹proto

7、编写message并放在proto文件夹下,有关编写规范和说明请参考官网文档 ,在这里我引用官网的例子,创建addressbook.proto代码如下:

  1. package  tutorial;
  2. option java_package = "com.example.tutorial" ;
  3. option java_outer_classname = "AddressBookProtos" ;
  4. message Person {
  5. required string name = 1 ;
  6. required int32 id = 2 ;         // Unique ID number for this person.
  7. optional string email = 3 ;
  8. enum  PhoneType {
  9. MOBILE = 0 ;
  10. HOME = 1 ;
  11. WORK = 2 ;
  12. }
  13. message PhoneNumber {
  14. required string number = 1 ;
  15. optional PhoneType type = 2  [ default  = HOME];
  16. }
  17. repeated PhoneNumber phone = 4 ;
  18. }
  19. // Our address book file is just one of these.
  20. message AddressBook {
  21. repeated Person person = 1 ;
  22. }
[java] view plaincopy
  1. package tutorial;
  2. option java_package = "com.example.tutorial";
  3. option java_outer_classname = "AddressBookProtos";
  4. message Person {
  5. required string name = 1;
  6. required int32 id = 2;        // Unique ID number for this person.
  7. optional string email = 3;
  8. enum PhoneType {
  9. MOBILE = 0;
  10. HOME = 1;
  11. WORK = 2;
  12. }
  13. message PhoneNumber {
  14. required string number = 1;
  15. optional PhoneType type = 2 [default = HOME];
  16. }
  17. repeated PhoneNumber phone = 4;
  18. }
  19. // Our address book file is just one of these.
  20. message AddressBook {
  21. repeated Person person = 1;
  22. }

8、编译addressbook.proto成指定的java类

命令行下进入编译器所在目录,执行如下命令

protoc -I=proto/ --java_out=src proto/addressbook.proto

其中,src为生成的java类的目标位置,这里我们选择项目的默认包,proto/addressbook.proto表示我们的proto文件,运行 后即生成java类,生成的java类被放在了package com.example.tutorial中。刚才我们指定的目标位置是src,为什么现在却被放在了这个包中呢?这和我们的 addressbook.proto文件中的option java_package = "com.example.tutorial";有关。欲了解更多,参考上节提到的官方文档。

9、现在有了生成的AddressBookProtos.java类,我们可以向文件里写入消息了,首先编写AddPerson.java,代码如下:

  1. import  com.example.tutorial.AddressBookProtos.AddressBook;
  2. import  com.example.tutorial.AddressBookProtos.Person;
  3. import  java.io.BufferedReader;
  4. import  java.io.FileInputStream;
  5. import  java.io.FileNotFoundException;
  6. import  java.io.FileOutputStream;
  7. import  java.io.InputStreamReader;
  8. import  java.io.IOException;
  9. import  java.io.PrintStream;
  10. class  AddPerson{
  11. // This function fills in a Person message based on user input.
  12. static  Person PromptForAddress(BufferedReader stdin,PrintStream stdout) throws  IOException{
  13. Person.Builder person = Person.newBuilder();
  14. stdout.print("Enter person ID: " );
  15. person.setId(Integer.valueOf(stdin.readLine()));
  16. stdout.print("Enter name: " );
  17. person.setName(stdin.readLine());
  18. stdout.print("Enter email address (blank for none): " );
  19. String email = stdin.readLine();
  20. if  (email.length() >  0 ){
  21. person.setEmail(email);
  22. }
  23. while  ( true ){
  24. stdout.print("Enter a phone number (or leave blank to finish): " );
  25. String number = stdin.readLine();
  26. if  (number.length() ==  0 ){
  27. break ;
  28. }
  29. Person.PhoneNumber.Builder phoneNumber = Person.PhoneNumber.newBuilder().setNumber(number);
  30. stdout.print("Is this a mobile, home, or work phone? " );
  31. String type = stdin.readLine();
  32. if  (type.equals( "mobile" )){
  33. phoneNumber.setType(Person.PhoneType.MOBILE);
  34. } else   if  (type.equals( "home" )) {
  35. phoneNumber.setType(Person.PhoneType.HOME);
  36. } else   if  (type.equals( "work" )) {
  37. phoneNumber.setType(Person.PhoneType.WORK);
  38. } else  {
  39. stdout.println("Unknown phone type.  Using default." );
  40. }
  41. person.addPhone(phoneNumber);
  42. }
  43. return  person.build();
  44. }
  45. // Main function: Reads the entire address book from a file,  adds one person based on user input,
  46. //then writes it back out to the same file.
  47. public   static   void  main(String[] args)  throws  Exception{
  48. if  (args.length !=  1 ) {
  49. System.err.println("Usage:  AddPerson ADDRESS_BOOK_FILE" );
  50. System.exit(-1 );
  51. }
  52. AddressBook.Builder addressBook = AddressBook.newBuilder();
  53. // Read the existing address book.
  54. try  {
  55. addressBook.mergeFrom(new  FileInputStream(args[ 0 ]));
  56. } catch  (FileNotFoundException e) {
  57. System.out.println(args[0 ] +  ": File not found.  Creating a new file." );
  58. }
  59. // Add an address.
  60. addressBook.addPerson(
  61. PromptForAddress(new  BufferedReader( new  InputStreamReader(System.in)), System.out));
  62. // Write the new address book back to disk.
  63. FileOutputStream output = new  FileOutputStream(args[ 0 ]);
  64. addressBook.build().writeTo(output);
  65. output.close();
  66. }
  67. }
[java] view plaincopy
  1. import com.example.tutorial.AddressBookProtos.AddressBook;
  2. import com.example.tutorial.AddressBookProtos.Person;
  3. import java.io.BufferedReader;
  4. import java.io.FileInputStream;
  5. import java.io.FileNotFoundException;
  6. import java.io.FileOutputStream;
  7. import java.io.InputStreamReader;
  8. import java.io.IOException;
  9. import java.io.PrintStream;
  10. class AddPerson{
  11. // This function fills in a Person message based on user input.
  12. static Person PromptForAddress(BufferedReader stdin,PrintStream stdout)throws IOException{
  13. Person.Builder person = Person.newBuilder();
  14. stdout.print("Enter person ID: ");
  15. person.setId(Integer.valueOf(stdin.readLine()));
  16. stdout.print("Enter name: ");
  17. person.setName(stdin.readLine());
  18. stdout.print("Enter email address (blank for none): ");
  19. String email = stdin.readLine();
  20. if (email.length() > 0){
  21. person.setEmail(email);
  22. }
  23. while (true){
  24. stdout.print("Enter a phone number (or leave blank to finish): ");
  25. String number = stdin.readLine();
  26. if (number.length() == 0){
  27. break;
  28. }
  29. Person.PhoneNumber.Builder phoneNumber = Person.PhoneNumber.newBuilder().setNumber(number);
  30. stdout.print("Is this a mobile, home, or work phone? ");
  31. String type = stdin.readLine();
  32. if (type.equals("mobile")){
  33. phoneNumber.setType(Person.PhoneType.MOBILE);
  34. } else if (type.equals("home")) {
  35. phoneNumber.setType(Person.PhoneType.HOME);
  36. } else if (type.equals("work")) {
  37. phoneNumber.setType(Person.PhoneType.WORK);
  38. } else {
  39. stdout.println("Unknown phone type.  Using default.");
  40. }
  41. person.addPhone(phoneNumber);
  42. }
  43. return person.build();
  44. }
  45. // Main function: Reads the entire address book from a file,  adds one person based on user input,
  46. //then writes it back out to the same file.
  47. public static void main(String[] args) throws Exception{
  48. if (args.length != 1) {
  49. System.err.println("Usage:  AddPerson ADDRESS_BOOK_FILE");
  50. System.exit(-1);
  51. }
  52. AddressBook.Builder addressBook = AddressBook.newBuilder();
  53. // Read the existing address book.
  54. try {
  55. addressBook.mergeFrom(new FileInputStream(args[0]));
  56. } catch (FileNotFoundException e) {
  57. System.out.println(args[0] + ": File not found.  Creating a new file.");
  58. }
  59. // Add an address.
  60. addressBook.addPerson(
  61. PromptForAddress(new BufferedReader(new InputStreamReader(System.in)), System.out));
  62. // Write the new address book back to disk.
  63. FileOutputStream output = new FileOutputStream(args[0]);
  64. addressBook.build().writeTo(output);
  65. output.close();
  66. }
  67. }

首先配置参数,也就是消息被序列化后存储的文件名,这里,我们就把参数设置成AddressBook.代码中提到,运行时如果文件不存在,将会创建文件并写入;如果存在,就写入。运行程序,按照提示输入消息。然后查看我们的项目路径下,将会产生AddressBook文件

10、上一步是将消息序列化到文件中,这一步将文件中的消息反序列化,类似地,我们创建一个类:ListPeople.java 代码如下:

  1. import  com.example.tutorial.AddressBookProtos.AddressBook;
  2. import  com.example.tutorial.AddressBookProtos.Person;
  3. import  java.io.FileInputStream;
  4. public   class  ListPeople {
  5. // Iterates though all people in the AddressBook and prints info about them.
  6. static   void  Print(AddressBook addressBook) {
  7. for  (Person person: addressBook.getPersonList()) {
  8. System.out.println("Person ID: "  + person.getId());
  9. System.out.println("  Name: "  + person.getName());
  10. if  (person.hasEmail()) {
  11. System.out.println("  E-mail address: "  + person.getEmail());
  12. }
  13. for  (Person.PhoneNumber phoneNumber : person.getPhoneList()) {
  14. switch  (phoneNumber.getType()) {
  15. case  MOBILE:
  16. System.out.print("  Mobile phone #: " );
  17. break ;
  18. case  HOME:
  19. System.out.print("  Home phone #: " );
  20. break ;
  21. case  WORK:
  22. System.out.print("  Work phone #: " );
  23. break ;
  24. }
  25. System.out.println(phoneNumber.getNumber());
  26. }
  27. }
  28. }
  29. // Main function:  Reads the entire address book from a file and prints all  the information inside.
  30. /**
  31. * @param args
  32. * @throws Exception
  33. */
  34. public   static   void  main(String[] args)  throws  Exception {
  35. if  (args.length !=  1 ) {
  36. System.err.println("Usage:  ListPeople ADDRESS_BOOK_FILE" );
  37. System.exit(-1 );
  38. }
  39. // Read the existing address book.
  40. AddressBook addressBook = AddressBook.parseFrom(new  FileInputStream(args[ 0 ]));
  41. Print(addressBook);
  42. }
  43. }
[java] view plaincopy
  1. import com.example.tutorial.AddressBookProtos.AddressBook;
  2. import com.example.tutorial.AddressBookProtos.Person;
  3. import java.io.FileInputStream;
  4. public class ListPeople {
  5. // Iterates though all people in the AddressBook and prints info about them.
  6. static void Print(AddressBook addressBook) {
  7. for (Person person: addressBook.getPersonList()) {
  8. System.out.println("Person ID: " + person.getId());
  9. System.out.println("  Name: " + person.getName());
  10. if (person.hasEmail()) {
  11. System.out.println("  E-mail address: " + person.getEmail());
  12. }
  13. for (Person.PhoneNumber phoneNumber : person.getPhoneList()) {
  14. switch (phoneNumber.getType()) {
  15. case MOBILE:
  16. System.out.print("  Mobile phone #: ");
  17. break;
  18. case HOME:
  19. System.out.print("  Home phone #: ");
  20. break;
  21. case WORK:
  22. System.out.print("  Work phone #: ");
  23. break;
  24. }
  25. System.out.println(phoneNumber.getNumber());
  26. }
  27. }
  28. }
  29. // Main function:  Reads the entire address book from a file and prints all  the information inside.
  30. /**
  31. * @param args
  32. * @throws Exception
  33. */
  34. public static void main(String[] args) throws Exception {
  35. if (args.length != 1) {
  36. System.err.println("Usage:  ListPeople ADDRESS_BOOK_FILE");
  37. System.exit(-1);
  38. }
  39. // Read the existing address book.
  40. AddressBook addressBook = AddressBook.parseFrom(new FileInputStream(args[0]));
  41. Print(addressBook);
  42. }
  43. }

运行程序,将会看到我们输入的消息体被遍历并打印出来了!

通过一个简单的例子,希望能够对大家有所帮助!!

protocol buffer的使用相关推荐

  1. 【C++】Google Protocol Buffer(protobuf)详解(一)

    1.简介 Google Protocol Buffer( 简称 Protobuf) 是 Google 公司内部的混合语言数据标准, Protocol Buffers 是一种轻便高效的结构化数据存储格式 ...

  2. Protocol Buffer Basics: C#

    Protocol Buffer 基础知识:c#    原文地址:https://developers.google.com/protocol-buffers/docs/csharptutorial 这 ...

  3. 跨语言RPC框架Hessian、Thrift、Protocol Buffer之间的选择

    为什么80%的码农都做不了架构师?>>>    总结在几者之间选择的考量: 1. 如果你不需要很多语言相互调用, 希望保持清晰的java接口代码(无任何业务不相关的接口继承和方法,属 ...

  4. Google Protocol Buffer 简单介绍

    以下内容主要整理自官方文档. 为什么使用 Protocol Buffers .proto文件 Protocol Buffers 语法 编译.proto文件 Protocol Buffers API 枚 ...

  5. python中使用 protocol buffer(Protobuf)

    项目中引入proto的依赖 [两种方法]: 方法1. 官网下载对应的语言包,https://github.com/protocolbuffers/protobuf/releases 这里选择pytho ...

  6. Protocol Buffer技术详解(语言规范)

     该系列Blog的内容主体主要源自于Protocol Buffer的官方文档,而代码示例则抽取于当前正在开发的一个公司内部项目的Demo.这样做的目的主要在于不仅可以保持Google文档的良好风格 ...

  7. Google Protocol Buffer 的使用和原理

    FROM : https://www.ibm.com/developerworks/cn/linux/l-cn-gpb/ Google Protocol Buffer 的使用和原理 Protocol ...

  8. Protocol Buffer搭建及示例

    本文来源:http://www.tanhao.me/code/150911.html/ Protocol Buffer(简称Protobuf或PB)是由Google推出的一种数据交换格式,与传统的XM ...

  9. Protocol Buffer数据编码

    这是一篇让你对Protocol Buffer知其然亦知其所以然的文档,即便你在并不了解这其中的技术细节和处理机制的情况下,仍然能够在你的应用程序中正常的使用Protocol Buffer,然而我相信, ...

  10. Protocol Buffer Java应用实例

    生成目标语言代码 下面的命令帮助我们将MyMessage.proto文件中定义的一组Protocol Buffer格式的消息编译成目标语言(Java)的代码.至于消息的内容,我们会在后面以分段的形式逐 ...

最新文章

  1. C++中的STL算法详解
  2. 三层架构,Struts2,SpringMVC实现原理图
  3. matlab plot函数_慧图大讲堂 | 一起来认识MATLAB吧!
  4. word2vector 讲的比较好的文章
  5. linux制作ext2磁盘镜像,linux--创建镜像挂载
  6. NSIS修改开始菜单中图标
  7. 重载练习3_实现重载的println方法
  8. IPMI远程管理一点记录
  9. (pytorch-深度学习系列)pytorch数据操作
  10. html伸缩布局,CSS3 伸缩布局(一)
  11. 思科模拟器企业网站服务器配置,思科模拟器服务器配置
  12. mysql connections
  13. python链接MySQL数据库
  14. 在C#中什么时候用分号?
  15. 用turtle绘图做一个钟表时钟
  16. 力扣刷题 DAY_64 回溯
  17. 单词短时间记忆法和艾宾浩斯遗忘曲线
  18. 打地鼠java代码流程图_51单片机 普中51 打地鼠游戏 仿真 程序 流程图
  19. Java使用POI实现导出Word文档
  20. 火山视窗树形框实现取所有根项目文本

热门文章

  1. 阶段3 1.Mybatis_12.Mybatis注解开发_8 mybatis注解开发使用二级缓存
  2. 关于Latent Dirichlet Allocation及Hierarchical LDA模型的必读文章和相关代码
  3. 阶段3 1.Mybatis_05.使用Mybatis完成CRUD_4 Mybatis的CRUD-查询一个和模糊查询
  4. 小战Java笔记_SE_Identifier(标识符)
  5. laravel 分页使用
  6. ucore 地址映射的几个阶段
  7. JAVA 基础 / 第八课:面向对象 / JAVA类的方法与实例方法
  8. 事件 event
  9. Windows 7 64位下使用ADB驱动
  10. 使用Redis存取数据+数据库存取(spring+java)