RecordIdManager.cs 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. using System.Collections.Concurrent;
  2. using System.Timers;
  3. using System.Xml;
  4. using Abp.Dependency;
  5. using Abp.Logging;
  6. using Abp.UI;
  7. using VberZero.Configuration;
  8. using VberZero.Tools.StringModel;
  9. using Timer = System.Timers.Timer;
  10. namespace VberZero.DomainService.AppGuids;
  11. public class RecordIdManager : ISingletonDependency
  12. {
  13. public RecordIdManager(IWebHostEnvironment env)
  14. {
  15. var cfg = env.GetAppConfiguration();
  16. Interval = cfg["RecordId:TimerInterval"]?.ValD() ?? 10;
  17. HasChanged = true;
  18. FileName = Path.Combine(env.ContentRootPath, cfg["RecordId:Path"] ?? VzConsts.ResourceBasePath,
  19. "Guids.Vzx");
  20. }
  21. //分钟
  22. private decimal Interval { get; }
  23. private bool HasChanged { get; set; }
  24. private string FileName { get; set; }
  25. /// <summary>
  26. /// 定时器
  27. /// </summary>
  28. private Timer _timer;
  29. private static ConcurrentDictionary<AppGuidType, RecordId> RecordIddDictionary { get; set; }
  30. /// <summary>
  31. /// 获取下一记录ID
  32. /// </summary>
  33. /// <param name="type"></param>
  34. /// <returns></returns>
  35. public int GetNextRecordId(AppGuidType type)
  36. {
  37. HasChanged = true;
  38. if (RecordIddDictionary.TryGetValue(type, out var record))
  39. {
  40. return record.GetNextId();
  41. }
  42. throw new UserFriendlyException("获取下一记录ID失败!");
  43. }
  44. /// <summary>
  45. /// 加载文件数据
  46. /// </summary>
  47. public void LoadDictionary(string fileName = null)
  48. {
  49. if (fileName.NotEmpty())
  50. {
  51. FileName = fileName;
  52. }
  53. if (!File.Exists(FileName))
  54. {
  55. //throw new Exception("未查询到Guid文件,请检查配置!");
  56. LogHelper.Logger.Error("【未查询到Guid文件,请检查配置!】");
  57. return;
  58. }
  59. RecordIddDictionary = new ConcurrentDictionary<AppGuidType, RecordId>();
  60. try
  61. {
  62. var xDoc = new XmlDocument();
  63. xDoc.Load(FileName ?? throw new InvalidOperationException());
  64. XmlNode xmlNode = xDoc.LastChild;
  65. if (xmlNode is { HasChildNodes: true })
  66. {
  67. foreach (XmlNode node in xmlNode.ChildNodes)
  68. {
  69. var record = new RecordId
  70. {
  71. IdType = (node.Attributes?["type"] != null ? node.Attributes["type"].Value : "")
  72. .GetEnumByName<AppGuidType>(),
  73. Step = (node.Attributes?["step"] != null ? node.Attributes["step"].Value : "").ValI(),
  74. LastId = (node.Attributes?["last-id"] != null ? node.Attributes["last-id"].Value : "")
  75. .ValI(),
  76. LastDate = (node.Attributes?["last-date"] != null
  77. ? node.Attributes["last-date"].Value
  78. : "").StrToDt()
  79. };
  80. if (!RecordIddDictionary.ContainsKey(record.IdType))
  81. {
  82. RecordIddDictionary.TryAdd(record.IdType, record);
  83. }
  84. }
  85. }
  86. //触发定时器执行
  87. ExecuteTimer();
  88. }
  89. catch (Exception e)
  90. {
  91. LogHelper.Logger.Error("Guid文件解析失败,请检查配置!", e);
  92. //LogHelper.LogException(e);
  93. //throw new Exception($"Guid文件解析失败,请检查配置!({e.Message})");
  94. }
  95. }
  96. /// <summary>
  97. /// 执行定时器
  98. /// </summary>
  99. private void ExecuteTimer()
  100. {
  101. if (_timer != null)
  102. {
  103. _timer.Stop();
  104. _timer.Close();
  105. _timer = null;
  106. }
  107. //分钟转换成毫秒
  108. var interval = Convert.ToDouble(Interval * 60 * 1000);
  109. _timer = new Timer(interval);
  110. _timer.Elapsed += Save;
  111. _timer.Enabled = true;
  112. _timer.AutoReset = true;
  113. _timer.Start();
  114. }
  115. /// <summary>
  116. /// 定时保存数据
  117. /// </summary>
  118. /// <param name="source"></param>
  119. /// <param name="ev"></param>
  120. private void Save(object source, ElapsedEventArgs ev)
  121. {
  122. if (!HasChanged)
  123. return;
  124. if (RecordIddDictionary == null)
  125. return;
  126. var str = "";
  127. foreach (var dic in RecordIddDictionary)
  128. {
  129. var record = dic.Value;
  130. str += $"<Guid type=\"{record.IdType}\" step=\"{record.Step}\" last-id=\"{record.LastId}\" last-date=\"{record.LastDate}\"></Guid>";
  131. }
  132. str = $"<Guids>{str}</Guids>";
  133. try
  134. {
  135. var xDoc = new XmlDocument { InnerXml = str };
  136. xDoc.Save(FileName);
  137. }
  138. catch (Exception e)
  139. {
  140. LogHelper.LogException(e);
  141. }
  142. HasChanged = false;
  143. }
  144. }