Persistence_Counter.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using Sers.Core.Module.Counter;
  5. using Sers.Gover.Base;
  6. using Vit.Core.Module.Log;
  7. using Vit.Core.Util.ConfigurationManager;
  8. using Vit.Extensions;
  9. namespace Sers.Gover.Persistence
  10. {
  11. public class Persistence_Counter
  12. {
  13. static readonly string[] filePath = new [] {"Data", "Sers", "Gover", "Counter.json" };
  14. /*
  15. Counter.json
  16. {
  17. "ApiStations":{
  18. "_sys_":{ counter}
  19. },
  20. "ApiServices":{
  21. "/_sys/api1":{counter},
  22. "/_sys/api2":{counter}
  23. }
  24. }
  25. */
  26. /// <summary>
  27. /// 持久化ApiStation所有Counter(demo: /Data/Sers/Gover/Counter.json)
  28. /// </summary>
  29. /// <param name="apiStationMng"></param>
  30. public static void SaveCounterToJsonFile(ApiStationMng apiStationMng)
  31. {
  32. try
  33. {
  34. #region (x.1)构建文件内容
  35. var apiStations= apiStationMng.ApiStation_GetAll();
  36. var counter_ApiStations = apiStations.ToDictionary(m => m.stationName, m => m.counter);
  37. var counter_ApiServices = apiStations.SelectMany(m=>m.apiServices.Values).ToDictionary(m => m.apiDesc?.ServiceKeyGet(), m => m.counter);
  38. var fileContent = new { ApiStations= counter_ApiStations, ApiServices= counter_ApiServices };
  39. #endregion
  40. //(x.2) 保存到文件
  41. JsonFile.SetToFile(fileContent, filePath);
  42. }
  43. catch (System.Exception ex)
  44. {
  45. Logger.Error(ex);
  46. }
  47. }
  48. public static void LoadCounterFromJsonFile(ApiStationMng apiStationMng)
  49. {
  50. try
  51. {
  52. //(x.1)载入文件
  53. var counterData = JsonFile.GetFromFile<Dictionary<string, Dictionary<string, Counter>>>(filePath);
  54. //(x.2)加载数据
  55. if (counterData.TryGetValue("ApiStations", out var counter_ApiStations))
  56. {
  57. foreach (var item in counter_ApiStations)
  58. {
  59. apiStationMng.ApiStation_GetOrAddByName(item.Key).counter.CopyDataFrom(item.Value);
  60. }
  61. }
  62. if (counterData.TryGetValue("ApiServices", out var counter_ApiServices))
  63. {
  64. foreach (var item in counter_ApiServices)
  65. {
  66. apiStationMng.ApiStation_GetOrAddByRoute(item.Key)?.ApiService_Get(item.Key)?.counter.CopyDataFrom(item.Value);
  67. }
  68. }
  69. }
  70. catch (Exception ex)
  71. {
  72. Logger.Error(ex);
  73. }
  74. }
  75. }
  76. }