protobuf对象二进制序列化存储

男娘i 2022-08-20 05:06 344阅读 0赞

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

demo:

  1. using System;
  2. namespace Tools
  3. {
  4. public class BufHelp
  5. {
  6. /// <summary>
  7. /// 对象锁
  8. /// </summary>
  9. private readonly static Object Locker = new Object();
  10. / <summary>
  11. / 读写分离锁
  12. / </summary>
  13. / <remarks>http://www.360doc.com/content/13/1216/09/10504424_337515446.shtml</remarks>
  14. //private static ReaderWriterLockSlim rwl = new ReaderWriterLockSlim();
  15. /// <summary>
  16. /// 序列化-表字段业务信息
  17. /// </summary>
  18. public static bool ProtoBufSerialize<T>(T model, string filename) where T : class
  19. {
  20. try
  21. {
  22. string binpath = Config.KeyCenter.KeyBaseDirectory + @"Config\";
  23. if (!System.IO.Directory.Exists(binpath))
  24. System.IO.Directory.CreateDirectory(binpath);
  25. lock (Locker)
  26. {
  27. using (var file = System.IO.File.Create(binpath + filename))
  28. {
  29. ProtoBuf.Serializer.Serialize<T>(file, model);
  30. return true;
  31. }
  32. }
  33. }
  34. catch
  35. {
  36. return false;
  37. }
  38. }
  39. public static T ProtoBufDeserialize<T>(string filename) where T : class
  40. {
  41. var dbpath = Config.KeyCenter.KeyBaseDirectory + @"Config\" + filename;
  42. if (System.IO.File.Exists(dbpath))
  43. {
  44. lock (Locker)
  45. {
  46. using (var file = System.IO.File.OpenRead(dbpath))
  47. {
  48. var result = ProtoBuf.Serializer.Deserialize<T>(file);
  49. return result;
  50. }
  51. }
  52. }
  53. return default(T);
  54. }
  55. }
  56. }
  57. /// <summary>
  58. /// 序列化
  59. /// </summary>
  60. public static string Serialize<T>(T t) where T : class
  61. {
  62. using (MemoryStream ms = new MemoryStream())
  63. {
  64. ProtoBuf.Serializer.Serialize<T>(ms, t);
  65. return Encoding.UTF8.GetString(ms.ToArray());
  66. }
  67. }
  68. /// <summary>
  69. /// 反序列化
  70. /// </summary>
  71. public static T DeSerialize<T>(string content) where T : class
  72. {
  73. using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(content)))
  74. {
  75. T t = ProtoBuf.Serializer.Deserialize<T>(ms);
  76. return t;
  77. }
  78. }

发表评论

表情:
评论列表 (有 0 条评论,344人围观)

还没有评论,来说两句吧...

相关阅读

    相关 protobuf 序列和反序列

    Protocol Buffers(protobuf)是一种轻量级的数据交换格式,可以用于结构化数据的序列化和反序列化。它使用二进制格式来编码数据,以提高传输效率和数据压缩...