zoukankan      html  css  js  c++  java
  • Google Protocol Buffers 入门

    Google Protocol Buffers 是一种轻便高效的结构化数据存储格式,可以用于结构化数据串行化,或者说序列化。它很适合做数据存储或 RPC 数据交换格式。可用于通讯协议、数据存储等领域的语言无关、平台无关、可扩展的序列化结构数据格式。目前支持主流的语言(javac++pythonc#go....)。

    具官方说法使用PB 进行序列化和反序列化性能是xml序列化和反序列化的20~100倍,在各种序列化和反序列化方式中,处于领先地位。

    PB的序列化结果是字节与字节的连接,省略了字段名称,在存储上也比其他方式要小,更节省空间。不过这样带来了可读性变差和调试困难。

    官方源码:https://github.com/google/protobuf

    各版本的编译结果下载地址:https://github.com/google/protobuf/releases

    官方介绍:https://developers.google.com/protocol-buffers/

    1、下载protoc

    在https://github.com/google/protobuf/releases中,可以看到多个系统的protoc文件:

    protoc-3.3.0-linux-x86_32.zip                           

    protoc-3.3.0-linux-x86_64.zip        

    protoc-3.3.0-osx-x86_32.zip           

    protoc-3.3.0-osx-x86_64.zip                          

    protoc-3.3.0-win32.zip

    下载后,解压就可以。

    2、在解压目录创建一个*.proto 文件。

    如:test.proto

    syntax = "proto3"; 

    message test{  

      double Id=1;   

    string Name=2;

    }

    syntax = "proto3"; 为指定一个版本,此含义为使用proto3

    message为关键字,test为类名

    double/string为类字段类型,Id/Name为字段属性,1/2为存储序号,定义后不可变

    详细定义和使用方法参考:https://developers.google.com/protocol-buffers/docs/proto3#simple

    3、生成各种语言的类文件

    protoc --cpp_out="./"  --java_out="./"   --csharp_out="./"  ./test.proto

    “./”为当前protoc所在目录,protoc为可执行文件

    4、序列化与反序列化(以下C#示例)

     Google.Protobuf.IMessage test= new test() {  Id= 3333555555234234.333, Name= "dfsdfsdfsdfsdfsdfsdfs"};  //创建test对象
    
     byte[] buf = null;
     using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
     {
         //序列化
         using (Google.Protobuf.CodedOutputStream output = new Google.Protobuf.CodedOutputStream(ms))
         {
            test.WriteTo(output);
         }
    
                        
         buf = ms.ToArray();
     }
    
     test newTest = new test();
     using (Google.Protobuf.CodedInputStream input = new Google.Protobuf.CodedInputStream(buf))
     {
         //反序列化
         newTest.MergeFrom(input);
     }
  • 相关阅读:
    @ExceptionHandler
    使用Vue.extend实现iview Upload在单文件上传时,拖拽多个文件给出错误提示
    spring 常用的注入方式
    SpringMVC框架
    Redis
    事务的隔离性以及隔离级别
    Qt的获取和安装
    C++ 指针delete 及 指针delete后赋值为NULL
    图形流水线
    freeglut的安装步骤
  • 原文地址:https://www.cnblogs.com/hobinly/p/7157481.html
Copyright © 2011-2022 走看看