上手protobuf

为什么要使用protobuf呢?

  项目中有一个查询带导出excel模块,查询的时候是分页,但导出excel是不分页的.用.Net自身的二进制序列化比较慢,到数据量一个,会报内存溢出.

1. protobuf-net下载

 https://github.com/mgravell/protobuf-net  

2. 解压下载,编译时遇到的问题

编译protobuf项目
生成时,错误提示
protobuf错误提示
修改之前c#语言版本
c#语言版本,protobuf项目的比较旧
将c#的版本修改为6.0

修改c#的版本

简单上手

using ProtoBuf;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;

namespace ProtoBufApp
{
    [ProtoContract]
    class People
    {
        [ProtoMember(1)]
        public int Id { get; set; }
        [ProtoMember(2)]
        public string Name { get; set; }
        [ProtoMember(3)]
        public int Age { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            //计时
            Stopwatch sw = new Stopwatch();
           
            //这里只是模拟100万数据
            List<People> list1 = new List<People>();
            Random random = new Random();
            People p1 = null;
            for (int i = 0; i < 1000000; i++)
            {
                p1 = new People()
                {
                    Id = i,
                    Name = "hello" + i,
                    Age = random.Next(1, 100)
                };
                list1.Add(p1);
            }

            sw.Start();
            using (var stream = File.Create("people.bin"))
            {
                Serializer.Serialize(stream, list1);                  //进行序列化
            }
            sw.Stop();
            Console.WriteLine($"->序列化耗时:{sw.ElapsedMilliseconds}ms");

            sw.Restart();

            List<People> list2 = null;
            using (var stream = File.OpenRead("people.bin"))
            {
                list2 = Serializer.Deserialize<List<People>>(stream); //进行反序列化
            }
            sw.Stop();
            Console.WriteLine($"->反序列化耗时:{sw.ElapsedMilliseconds}ms");

            Console.ReadKey();
        }
    }
}

效果(还是比自身二进制序列化快的)

protobuf效果
后期慢慢集成到wcf的服务中去.

秋风 2017-02-28