Google ProtoBuf在C#中的简单应用

简介

什么是 Google Protocol Buffer? 假如您在网上搜索,应该会获得相似这样的文字介绍:php

Google Protocol Buffer( 简称 Protobuf) 是 Google 公司内部的混合语言数据标准,目前已经正在使用的有超过 48,162 种报文格式定义和超过 12,183 个 .proto 文件。他们用于 RPC 系统和持续数据存储系统。json

Protocol Buffers 是一种轻便高效的结构化数据存储格式,能够用于结构化数据串行化,或者说序列化。它很适合作数据存储或 RPC 数据交换格式。可用于通信协议、数据存储等领域的语言无关、平台无关、可扩展的序列化结构数据格式。目前提供了 C++、Java、Python 三种语言的 API。windows

说一千道一万,Google Protocol Buffer是一个序列化数据结构好帮手,  相对于XML、二进制序列化方式,Protobuf效率较高,支持数据量较大,protobuf序列化后的大小是json的1/10,xml格式的1/20,是二进制序列化的1/10 (具体本人未测试过,数据由此篇文章获得:protobuf效率)数据结构

C#中怎么使用?

1、准备工做

  1. Visual Studio 2019(其余版本亦可)
  2. Nuget安装:Google.Protobuf和Google.Protobuf.Tools
  3. 准备.proto文件

2、关于proto文件

使用ProtoBuf,主要有两个操做:序列化和反序列化。这两个操做都须要协议描述文件,也就是.proto文件。若是要使用protobuf存储自定义的数据,就要本身编写proto文件,若是要读取其余的ProtoBuf序列化文件,就要先知道要读取的ProtoBuf序列化文件的协议,也就是要得到对应的.proto文件,这是一个必须条件,没有对应的proto文件,就没法正确打开ProtoBuf序列化文件。工具

3、步骤

一、安装Google.Protobuf和Google.Protobuf.Tools的Nuget包测试

Google ProtoBuf在C#中的简单应用安装Nuget包google

二、在Google.Protobuf.Tools下找到编译工具protoc.exe,个人电脑中路径是:C:\Users\admin.nuget\packages\google.protobuf.tools\3.10.1\tools\windows_x64,在此目录之上,还有不少版本,看您程序具体版本及tools版本而定。spa

三、准备好协议描述文件xx.proto,须要注意的是,proto文件之间能够互相引用,要正常使用,必须把全部相关的proto文件都准备好。下面是我本身写的一个测试文件test.proto:.net

syntax = "proto3";
option cc_enable_arenas = true;

package Test;

message TestContact {
	int32 ID = 1;
	string Address = 2;
	string Name = 3;
}

四、生成解码器code

  1. 创建两个文件夹,一个名为src,另外一个为gen
  2. 把准备好的proto文件所有放到src中,如个人test.proto
  3. 运行命令:.\protoc.exe –proto_path=src –csharp_out=gen test.proto
  4. 把全部的proto文件都生成一遍
  5. 在gen文件夹中,会发现有等量的.cs文件,这就是对应的解码器,咱们要把他们放进本身的工程中。

Google ProtoBuf在C#中的简单应用个人代码目录结构Google ProtoBuf在C#中的简单应用test.protoGoogle ProtoBuf在C#中的简单应用生成解码器Google ProtoBuf在C#中的简单应用Google ProtoBuf在C#中的简单应用protoC#部分代码

五、打开安装了Google.Protobuf和Google.Protobuf.Tools的Nuget包的C#工程,把刚刚生成的解码器导入工程中。

Google ProtoBuf在C#中的简单应用我把tools工具和proto文件及proto cs文件一块儿放入工程的代码结构

六、具体使用代码

using Google.Protobuf;
using System;
using System.IO;
using Test;

namespace protoctest
{
    class Program
    {
        static void Main(string[] args)
        {
            TestContact t = new TestContact();
            t.ID = 1;
            t.Name = "xiao ming";
            t.Address = "Cheng Du";
            Console.WriteLine($"序列化以前:{t}");

            //序列化操做
            byte[] data = new byte[t.CalculateSize()];
            using (CodedOutputStream cos = new CodedOutputStream(data))
            {
                t.WriteTo(cos);
                //data = cos.to.ToArray();
            }

            //反序列化操做
            TestContact t1 = TestContact.Parser.ParseFrom(data);
            Console.WriteLine($"反序列化获得:{t1}");

            Console.ReadKey();
        }
    }
}

七、运行效果以下

Google ProtoBuf在C#中的简单应用运行效果

4、代码

代码已上传CSDN:C#使用Google ProtoBuf例子

参考文章以下:

  1. Google Protocol Buffers
  2. Yowko’s Notes
  3. Angle_Cal

 

发布者:沙漠尽头的狼,转转请注明出处:https://lsq6.com/index.php/2019/11/11/google-protobuf-forcharp/

相关文章
相关标签/搜索