C# 實現 Snowflake演算法生成唯一性Id
阿新 • • 發佈:2018-12-29
參考地址:https://blog.csdn.net/w200221626/article/details/52064976
/// <summary> /// 動態生產有規律的ID /// </summary> public class Snowflake { private static long machineId;//機器ID private static long datacenterId = 0L;//資料ID private static long sequence = 0L;//計數從零開始private static long twepoch = 687888001020L; //唯一時間隨機量 private static long machineIdBits = 5L; //機器碼位元組數 private static long datacenterIdBits = 5L;//資料位元組數 public static long maxMachineId = -1L ^ -1L << (int)machineIdBits; //最大機器ID private static long maxDatacenterId = -1L^ (-1L << (int)datacenterIdBits);//最大資料ID private static long sequenceBits = 12L; //計數器位元組數,12個位元組用來儲存計數碼 private static long machineIdShift = sequenceBits; //機器碼資料左移位數,就是後面計數器佔用的位數 private static long datacenterIdShift = sequenceBits + machineIdBits; privatestatic long timestampLeftShift = sequenceBits + machineIdBits + datacenterIdBits; //時間戳左移動位數就是機器碼+計數器總位元組數+資料位元組數 public static long sequenceMask = -1L ^ -1L << (int)sequenceBits; //一微秒內可以產生計數,如果達到該值則等到下一微妙在進行生成 private static long lastTimestamp = -1L;//最後時間戳 private static object syncRoot = new object();//加鎖物件 static Snowflake snowflake; public static Snowflake Instance() { if (snowflake == null) snowflake = new Snowflake(); return snowflake; } public Snowflake() { Snowflakes(0L, -1); } public Snowflake(long machineId) { Snowflakes(machineId, -1); } public Snowflake(long machineId, long datacenterId) { Snowflakes(machineId, datacenterId); } private void Snowflakes(long machineId, long datacenterId) { if (machineId >= 0) { if (machineId > maxMachineId) { throw new Exception("機器碼ID非法"); } Snowflake.machineId = machineId; } if (datacenterId >= 0) { if (datacenterId > maxDatacenterId) { throw new Exception("資料中心ID非法"); } Snowflake.datacenterId = datacenterId; } } /// <summary> /// 生成當前時間戳 /// </summary> /// <returns>毫秒</returns> private static long GetTimestamp() { return (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds; } /// <summary> /// 獲取下一微秒時間戳 /// </summary> /// <param name="lastTimestamp"></param> /// <returns></returns> private static long GetNextTimestamp(long lastTimestamp) { long timestamp = GetTimestamp(); if (timestamp <= lastTimestamp) { timestamp = GetTimestamp(); } return timestamp; } /// <summary> /// 獲取長整形的ID /// </summary> /// <returns></returns> public long GetId() { lock (syncRoot) { long timestamp = GetTimestamp(); if (Snowflake.lastTimestamp == timestamp) { //同一微妙中生成ID sequence = (sequence + 1) & sequenceMask; //用&運算計算該微秒內產生的計數是否已經到達上限 if (sequence == 0) { //一微妙內產生的ID計數已達上限,等待下一微妙 timestamp = GetNextTimestamp(Snowflake.lastTimestamp); } } else { //不同微秒生成ID sequence = 0L; } if (timestamp < lastTimestamp) { throw new Exception("時間戳比上一次生成ID時時間戳還小,故異常"); } Snowflake.lastTimestamp = timestamp; //把當前時間戳儲存為最後生成ID的時間戳 long Id = ((timestamp - twepoch) << (int)timestampLeftShift) | (datacenterId << (int)datacenterIdShift) | (machineId << (int)machineIdShift) | sequence; return Id; } } }
測試程式碼:
class Program { static void Main(string[] args) { var blockingCollection = new BlockingCollection<long>(); List<Task> tasks = new List<Task>(); for (int i = 0; i < 100; i++) { var task = Task.Run(() => { for (int j = 0; j < 10000; j++) { //blockingCollection.Add(Snowflake.Instance().GetId());//一臺機器 blockingCollection.Add(new Snowflake(1,1).GetId());//多臺機器 } }); tasks.Add(task); } Task.WaitAll(tasks.ToArray()); Console.WriteLine(blockingCollection.Distinct().Count()); Console.ReadKey(); } }