SnowflakeID.cs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. using Microsoft.Extensions.Options;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Text;
  5. namespace TEAMModelOS.SDK.DI
  6. {
  7. public class SnowflakeId
  8. {
  9. private readonly IOptionsMonitor<SnowflakeIDOptions> _optionsMonitor;
  10. // 開始時間截((new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc)-Jan1st1970).TotalMilliseconds)
  11. private const long twepoch = 1577836800000L;
  12. // 機器ID所佔的位數
  13. private const int workerIdBits = 5;
  14. // 數據標識ID所佔的位數
  15. private const int datacenterIdBits = 5;
  16. // 支持的最大機器ID,結果是31 (這個移位算法可以很快的計算出幾位二進制數所能表示的最大十進制數)
  17. private const long maxWorkerId = -1L ^ (-1L << workerIdBits);
  18. // 支持的最大數據標識ID,結果是31
  19. private const long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
  20. // 序列在ID中佔的位數
  21. private const int sequenceBits = 12;
  22. // 數據標識ID向左移17位(12+5)
  23. private const int datacenterIdShift = sequenceBits + workerIdBits;
  24. // 機器ID向左移12位
  25. private const int workerIdShift = sequenceBits;
  26. // 時間截向左移22位(5+5+12)
  27. private const int timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
  28. // 生成序列的掩碼,這里為4095 (0b111111111111=0xfff=4095)
  29. private const long sequenceMask = -1L ^ (-1L << sequenceBits);
  30. // 毫秒內序列(0~4095)
  31. private long sequence = 0L;
  32. // 上次生成ID的時間截
  33. private long lastTimestamp = -1L;
  34. // 數據中心ID(0~31,China請填8,Global請填1)
  35. public long DatacenterId { get; private set; }
  36. // 工作機器ID(0~31,依照數據中心,各地區自定)
  37. public long WorkerId { get; private set; }
  38. /// <summary>
  39. /// 分散式ID產生器 (Snowflake算法,支援線程安全)
  40. /// </summary>
  41. /// <param name="datacenterId">數據中心ID (0~31)</param>
  42. /// <param name="workerId">工作機器ID (0~31)</param>
  43. public SnowflakeId(IOptionsMonitor<SnowflakeIDOptions> optionsMonitor)
  44. {
  45. if (optionsMonitor == null) throw new ArgumentNullException(nameof(optionsMonitor));
  46. _optionsMonitor = optionsMonitor;
  47. this.DatacenterId = optionsMonitor.CurrentValue.DatacenterId;
  48. this.WorkerId = optionsMonitor.CurrentValue.WorkerId;
  49. }
  50. /// <summary>
  51. /// 獲得下一個ID
  52. /// </summary>
  53. /// <returns></returns>
  54. public long NextId()
  55. {
  56. lock (this)
  57. {
  58. long timestamp = GetCurrentTimestamp();
  59. if (timestamp > lastTimestamp) //時間戳改變,毫秒內序列重置
  60. {
  61. sequence = 0L;
  62. }
  63. else if (timestamp == lastTimestamp) //如果是同一時間生成的,則進行毫秒內序列
  64. {
  65. sequence = (sequence + 1) & sequenceMask;
  66. if (sequence == 0) //毫秒內序列溢出
  67. {
  68. timestamp = GetNextTimestamp(lastTimestamp); //阻塞到下一個毫秒,獲得新的時間戳
  69. }
  70. }
  71. else //當前時間小於上一次ID生成的時間戳,證明系統時鐘被回撥,此時需要做回撥處理
  72. {
  73. sequence = (sequence + 1) & sequenceMask;
  74. if (sequence > 0)
  75. {
  76. timestamp = lastTimestamp; //停留在最後一次時間戳上,等待系統時間追上後即完全度過了時鐘回撥問題
  77. }
  78. else //毫秒內序列溢出
  79. {
  80. timestamp = lastTimestamp + 1; //直接進位到下一個毫秒
  81. }
  82. //throw new Exception(string.Format("Clock moved backwards. Refusing to generate id for {0} milliseconds", lastTimestamp - timestamp));
  83. }
  84. lastTimestamp = timestamp; //上次生成ID的時間截
  85. //移位並通過或運算拼到一起組成64位的ID
  86. var id = ((timestamp - twepoch) << timestampLeftShift)
  87. | (DatacenterId << datacenterIdShift)
  88. | (WorkerId << workerIdShift)
  89. | sequence;
  90. return id;
  91. }
  92. }
  93. /// <summary>
  94. /// 解析分散式ID
  95. /// </summary>
  96. /// <returns></returns>
  97. public string ParseId(long Id)
  98. {
  99. StringBuilder sb = new StringBuilder();
  100. var timestamp = (Id >> timestampLeftShift);
  101. var time = Jan1st1970.AddMilliseconds(timestamp + twepoch);
  102. sb.Append(time.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss:fff"));
  103. var datacenterId = (Id ^ (timestamp << timestampLeftShift)) >> datacenterIdShift;
  104. sb.Append("_" + datacenterId);
  105. var workerId = (Id ^ ((timestamp << timestampLeftShift) | (datacenterId << datacenterIdShift))) >> workerIdShift;
  106. sb.Append("_" + workerId);
  107. var sequence = Id & sequenceMask;
  108. sb.Append("_" + sequence);
  109. return sb.ToString();
  110. }
  111. /// <summary>
  112. /// 解析分散式ID,并转换为时间字符串。
  113. /// </summary>
  114. /// <returns></returns>
  115. public string ParseIdToTimeString(long Id, string format = "yyyy-MM-dd HH:mm:ss")
  116. {
  117. var timestamp = (Id >> timestampLeftShift);
  118. var time = Jan1st1970.AddMilliseconds(timestamp + twepoch);
  119. string timeString= time.ToLocalTime().ToString(format);
  120. return timeString;
  121. }
  122. /// <summary>
  123. /// 解析分散式ID,并转换为时间戳。
  124. /// </summary>
  125. /// <returns></returns>
  126. public long ParseIdToTimeStamp(long Id)
  127. {
  128. var timestamp = (Id >> timestampLeftShift);
  129. long stime = timestamp + twepoch;
  130. return stime;
  131. }
  132. /// <summary>
  133. /// 阻塞到下一個毫秒,直到獲得新的時間戳
  134. /// </summary>
  135. /// <param name="lastTimestamp">上次生成ID的時間截</param>
  136. /// <returns>當前時間戳</returns>
  137. private static long GetNextTimestamp(long lastTimestamp)
  138. {
  139. long timestamp = GetCurrentTimestamp();
  140. while (timestamp <= lastTimestamp)
  141. {
  142. timestamp = GetCurrentTimestamp();
  143. }
  144. return timestamp;
  145. }
  146. /// <summary>
  147. /// 獲取當前時間戳
  148. /// </summary>
  149. /// <returns></returns>
  150. private static long GetCurrentTimestamp()
  151. {
  152. return DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  153. //return (long)(DateTime.UtcNow - Jan1st1970).TotalMilliseconds;
  154. }
  155. private static readonly DateTime Jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
  156. }
  157. }