Protobuf

主要分2种

P1:Google.Protobuf:分v2和v3;

V3的类型对照表,地址见这里

V2的类型对照表,见这里

 

V3的用法

1、NET4.5的项目,安装Nuget包<Google.Protobuf>和<Google.Protobuf.Tools>

2、编写proto文件,类型参照上文定义;放一个demo.proto

syntax = "proto3";
package protobuf_unittest_import;
option csharp_namespace = "Export.DAL";

message ListFloat
{
repeated float items =1;
}

message CircleInfoBuf
    {
         int32 No =1;
         string Name =2;
         float Diameter =3;
         float Length =4;
         ListFloat Points =5;
    }

3、运行\packages\Google.Protobuf.Tools.3.9.1\tools\windows_x64下的protoc.exe,执行命令,转成cs代码;

protoc.exe --proto_path=所在目录 --csharp_out=生成的目录   demo.proto 

4、引用此cs文件,编写其他代码

5、序列化和反序列化

序列化

            string bufFile = "";
            using (FileStream fs = new FileStream(bufFile, FileMode.CreateNew))
            {
                using (CodedOutputStream cos = new CodedOutputStream(fs))
                {
                    list.WriteTo(cos);//需序列化的对象
                    fs.Flush();
                }
            }

反序列化

            using (FileStream fs = new FileStream(bufFile, FileMode.Open))
            {
                using (CodedInputStream cos = new CodedInputStream(fs))
                {
                    CircleInfoBuf list = CircleInfoBuf.Parser.ParseFrom(cos);
                    return list;
                }
            }

 

P2:protobuf-net

1、定义类

 

 [ProtoContract]
 public class CircleInfo
    {
        [ProtoMember(1)]
        public int No { get; set; }
        [ProtoMember(2)]
        public string Name { get; set; }
        [ProtoMember(3)]
        public float Diameter { get; set; }
        [ProtoMember(4)]
        public float Length { get; set; }
        [ProtoMember(5)]
        public float[] Points { get; set; }
    }

 序列化

            string bufFile = "";
            using (FileStream fs = new FileStream(bufFile, FileMode.OpenOrCreate))
            {
                ProtoBuf.Serializer.Serialize(fs, list);//需要序列化的对象
                fs.Flush();
            }

反序列化

        T Load<T>(string bufFile)
        {
            T list = default(T);
            using (FileStream fs = new FileStream(bufFile, FileMode.Open))
            {
                list = ProtoBuf.Serializer.Deserialize<T>(fs);
            }
            return list;
        }

------------------------------

对比性能测试Google.Protobuf(3.9.1.0)、.protobuf(2.4.0.0)-net和Json(Newtonsoft.Json 12.0.0.0),

序列化和反序列化的时间

Google.Protobuf > protobuf-net > Json

------------------------------

posted @ 2019-08-14 15:57  feedback  阅读(282)  评论(0编辑  收藏  举报