欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

protobuf对象二进制序列化存储(详解)

程序员文章站 2023-10-31 12:18:58
首先下载protobuf库,可以用nuget。 demo: using system; namespace tools { public clas...

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

demo:

using system;

namespace tools
{
  public class bufhelp
  {
    /// <summary>
    /// 对象锁
    /// </summary>
    private readonly static object locker = new object();
    ///// <summary>
    ///// 读写分离锁
    ///// </summary>
    ///// <remarks>aaaaa</remarks>
    //private static readerwriterlockslim rwl = new readerwriterlockslim();

    /// <summary>
    /// 序列化-表字段业务信息
    /// </summary>
    public static bool protobufserialize<t>(t model, string filename) where t : class
    {
      try
      {
        string binpath = 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<t>(file, model);
            return true;
          }
        }
      }
      catch
      {
        return false;
      }
    }

    public static t protobufdeserialize<t>(string filename) 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<t>(file);
            return result;
          }
        }
      }

      return default(t);
    }
  }
}/// <summary>
    /// 序列化
    /// </summary>
    public static string serialize<t>(t t) where t : class
    {
      using (memorystream ms = new memorystream())
      {
        protobuf.serializer.serialize<t>(ms, t);
        return encoding.utf8.getstring(ms.toarray());
      }
    }
    /// <summary>
    /// 反序列化
    /// </summary>
    public static t deserialize<t>(string content) where t : class
    {
      using (memorystream ms = new memorystream(encoding.utf8.getbytes(content)))
      {
        t t = protobuf.serializer.deserialize<t>(ms);
        return t;
      }
    }

以上这篇protobuf对象二进制序列化存储(详解)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。