protobuf对象二进制序列化存储

作者:袖梨 2022-06-25

首先下载protobuf库,可以用Nuget。

demo:

 

 代码如下 复制代码

usingSystem;

 

namespaceTools

{

  publicclassBufHelp

  {

    ///

    /// 对象锁

    ///

    privatereadonlystaticObject Locker =newObject();

    /////

    ///// 读写分离锁

    /////

    ///// aaaaa

    //private static ReaderWriterLockSlim rwl = new ReaderWriterLockSlim();

 

    ///

    /// 序列化-表字段业务信息

    ///

    publicstaticboolProtoBufSerialize(T model,stringfilename) where T :class

    {

      try

      {

        stringbinpath = Config.KeyCenter.KeyBaseDirectory +@"Config";

 

        if(!System.IO.Directory.Exists(binpath))

          System.IO.Directory.CreateDirectory(binpath);

 

        lock(Locker)

        {

          using(var file = System.IO.File.Create(binpath + filename))

          {

            ProtoBuf.Serializer.Serialize(file, model);

            returntrue;

          }

        }

      }

      catch

      {

        returnfalse;

      }

    }

 

    publicstaticT ProtoBufDeserialize(stringfilename) where T :class

    {

      var dbpath = Config.KeyCenter.KeyBaseDirectory +@"Config"+ filename;

 

      if(System.IO.File.Exists(dbpath))

      {

        lock(Locker)

        {

          using(var file = System.IO.File.OpenRead(dbpath))

          {

            var result = ProtoBuf.Serializer.Deserialize(file);

            returnresult;

          }

        }

      }

 

      returndefault(T);

    }

  }

}///

    /// 序列化

    ///

    publicstaticstringSerialize(T t) where T :class

    {

      using(MemoryStream ms =newMemoryStream())

      {

        ProtoBuf.Serializer.Serialize(ms, t);

        returnEncoding.UTF8.GetString(ms.ToArray());

      }

    }

    ///

    /// 反序列化

    ///

    publicstaticT DeSerialize(stringcontent) where T :class

    {

      using(MemoryStream ms =newMemoryStream(Encoding.UTF8.GetBytes(content)))

      {

        T t = ProtoBuf.Serializer.Deserialize(ms);

        returnt;

      }

    }

 

相关文章

精彩推荐