概述

分布式系统中,有一些需要使用全局唯一ID的场景,这种时候为了防止ID冲突可以使用36位的UUID,但是UUID有一些缺点,首先他相对比较长,另外UUID一般是无序的。有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。而twitter的snowflake解决了这种需求,最初Twitter把存储系统从MySQL迁移到Cassandra,因为Cassandra没有顺序ID生成机制,所以开发了这样一套全局唯一ID生成服务。 该项目地址为:https://github.com/twitter/snowflake是用Scala实现的。 python版详见开源项目https://github.com/erans/pysnowflake。
结构 snowflake的结构如下(每部分用-分开):
0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000
第一位为未使用,接下来的41位为毫秒级时间(41位的长度可以使用69年),然后是5位datacenterId和5位workerId(10位的长度最多支持部署1024个节点) ,最后12位是毫秒内的计数(12位的计数顺序号支持每个节点每毫秒产生4096个ID序号)
一共加起来刚好64位,为一个Long型。(转换成字符串长度为18)
snowflake生成的ID整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞(由datacenter和workerId作区分),并且效率较高。据说:snowflake每秒能够产生26万个ID。
Twitter分布式自增ID算法snowflake(雪花算法) - 图1
上图中主要由4个部分组成:
第一部分,1位为标识位,不用。
第二部分,41位,用来记录当前时间与标记时间twepoch的毫秒数的差值,41位的时间截,可以使用69年,T = (1L << 41) / (1000L 60 60 24 365) = 69
第三部分,10位,用来记录当前节点的信息,支持2的10次方台机器
第四部分,12位,用来支持每个节点每毫秒(同一机器,同一时间截)产生4096个ID序号

源码(C#版本源码)

  1. using System;
  2. public class Program
  3. {
  4. public static void Main()
  5. {
  6. //调用方法:
  7. IdWorker idworker = new IdWorker(1);
  8. for (int i = 0; i < 1000; i++)
  9. {
  10. Console.WriteLine(idworker.nextId().ToString());
  11. }
  12. }
  13. }
  14. public class IdWorker
  15. {
  16. //机器ID
  17. private static long workerId;
  18. private static long twepoch = 687888001020L; //唯一时间,这是一个避免重复的随机量,自行设定不要大于当前时间戳
  19. private static long sequence = 0L;
  20. private static int workerIdBits = 4; //机器码字节数。4个字节用来保存机器码(定义为Long类型会出现,最大偏移64位,所以左移64位没有意义)
  21. public static long maxWorkerId = -1L ^ -1L << workerIdBits; //最大机器ID
  22. private static int sequenceBits = 10; //计数器字节数,10个字节用来保存计数码
  23. private static int workerIdShift = sequenceBits; //机器码数据左移位数,就是后面计数器占用的位数
  24. private static int timestampLeftShift = sequenceBits + workerIdBits; //时间戳左移动位数就是机器码和计数器总字节数
  25. public static long sequenceMask = -1L ^ -1L << sequenceBits; //一微秒内可以产生计数,如果达到该值则等到下一微妙在进行生成
  26. private long lastTimestamp = -1L;
  27. /// <summary>
  28. /// 机器码
  29. /// </summary>
  30. /// <param name="workerId"></param>
  31. public IdWorker(long workerId)
  32. {
  33. if (workerId > maxWorkerId || workerId < 0)
  34. throw new Exception(string.Format("worker Id can't be greater than {0} or less than 0 ", workerId));
  35. IdWorker.workerId = workerId;
  36. }
  37. public long nextId()
  38. {
  39. lock (this)
  40. {
  41. long timestamp = timeGen();
  42. if (this.lastTimestamp == timestamp)
  43. {
  44. //同一微妙中生成ID
  45. IdWorker.sequence = (IdWorker.sequence + 1) & IdWorker.sequenceMask; //用&运算计算该微秒内产生的计数是否已经到达上限
  46. if (IdWorker.sequence == 0)
  47. {
  48. //一微妙内产生的ID计数已达上限,等待下一微妙
  49. timestamp = tillNextMillis(this.lastTimestamp);
  50. }
  51. }
  52. else
  53. {
  54. //不同微秒生成ID
  55. IdWorker.sequence = 0; //计数清0
  56. }
  57. if (timestamp < lastTimestamp)
  58. {
  59. //如果当前时间戳比上一次生成ID时时间戳还小,抛出异常,因为不能保证现在生成的ID之前没有生成过
  60. throw new Exception(string.Format("Clock moved backwards. Refusing to generate id for {0} milliseconds",
  61. this.lastTimestamp - timestamp));
  62. }
  63. this.lastTimestamp = timestamp; //把当前时间戳保存为最后生成ID的时间戳
  64. long nextId = (timestamp - twepoch << timestampLeftShift) | IdWorker.workerId << IdWorker.workerIdShift | IdWorker.sequence;
  65. return nextId;
  66. }
  67. }
  68. /// <summary>
  69. /// 获取下一微秒时间戳
  70. /// </summary>
  71. /// <param name="lastTimestamp"></param>
  72. /// <returns></returns>
  73. private long tillNextMillis(long lastTimestamp)
  74. {
  75. long timestamp = timeGen();
  76. while (timestamp <= lastTimestamp)
  77. {
  78. timestamp = timeGen();
  79. }
  80. return timestamp;
  81. }
  82. /// <summary>
  83. /// 生成当前时间戳
  84. /// </summary>
  85. /// <returns></returns>
  86. private long timeGen()
  87. {
  88. return (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
  89. }
  90. }

实例

  1. SnowFlakeUtil.GetNextId().ToString();//生成雪花ID
  2. public static class SnowFlakeUtil
  3. {
  4. private static SnowflakeIdWorker _woker;
  5. static SnowFlakeUtil()
  6. {
  7. _woker = new SnowflakeIdWorker(ConvertUtil.ToLong(WebConfig.MachineCode),ConvertUtil.ToLong(WebConfig.IdcCode));
  8. LogUtil.Debug($"SnowflakeIdWorker初始化,{WebConfig.MachineCode},{WebConfig.IdcCode}");
  9. }
  10. public static long GetNextId()
  11. {
  12. return _woker.nextId();
  13. }
  14. }
  15. public class SnowflakeIdWorker
  16. {
  17. private long machinecode;
  18. private long datacentercode;
  19. private long sequence = 0L;
  20. private static long twepoch = 1288834974657L;
  21. private static long workerIdBits = 5L;
  22. private static long datacenterIdBits = 5L;
  23. private static long maxWorkerId = -1L ^ (-1L << (int)workerIdBits);
  24. private static long maxDatacenterId = -1L ^ (-1L << (int)datacenterIdBits);
  25. private static long sequenceBits = 12L;
  26. private long workerIdShift = sequenceBits;
  27. private long datacenterIdShift = sequenceBits + workerIdBits;
  28. private long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
  29. private long sequenceMask = -1L ^ (-1L << (int)sequenceBits);
  30. private long lastTimestamp = -1L;
  31. private static object syncRoot = new object();
  32. public SnowflakeIdWorker(long machinecode, long datacentercode)
  33. {
  34. // sanity check for workerId
  35. if (machinecode > maxWorkerId || machinecode < 0)
  36. {
  37. throw new ArgumentException(string.Format("worker Id can't be greater than {0} or less than 0", maxWorkerId));
  38. }
  39. if (datacentercode > maxDatacenterId || datacentercode < 0)
  40. {
  41. throw new ArgumentException(string.Format("datacenter Id can't be greater than {0} or less than 0", maxDatacenterId));
  42. }
  43. this.machinecode = machinecode;
  44. this.datacentercode = datacentercode;
  45. }
  46. public long nextId()
  47. {
  48. lock (syncRoot)
  49. {
  50. long timestamp = timeGen();
  51. if (timestamp < lastTimestamp)
  52. {
  53. throw new ApplicationException(string.Format(
  54. "Clock moved backwards. Refusing to generate id for {0} milliseconds",
  55. lastTimestamp - timestamp));
  56. }
  57. if (lastTimestamp == timestamp)
  58. {
  59. sequence = (sequence + 1) & sequenceMask;
  60. if (sequence == 0)
  61. {
  62. timestamp = tilNextMillis(lastTimestamp);
  63. }
  64. }
  65. else
  66. {
  67. sequence = 0L;
  68. }
  69. lastTimestamp = timestamp;
  70. return ((timestamp - twepoch) << (int)timestampLeftShift) |
  71. (datacentercode << (int)datacenterIdShift) |
  72. (machinecode << (int)workerIdShift) | sequence;
  73. }
  74. }
  75. protected long tilNextMillis(long lastTimestamp)
  76. {
  77. long timestamp = timeGen();
  78. while (timestamp <= lastTimestamp)
  79. {
  80. timestamp = timeGen();
  81. }
  82. return timestamp;
  83. }
  84. protected long timeGen()
  85. {
  86. return (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
  87. }
  88. }

源码(Java版本源码)

  1. /**
  2. * Twitter_Snowflake<br>
  3. * SnowFlake的结构如下(每部分用-分开):<br>
  4. * 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000 <br>
  5. * SnowFlake的优点是,整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞(由数据中心ID和机器ID作区分)
  6. */
  7. public class SnowflakeIdWorker {
  8. /** 开始时间截 (2015-01-01) */
  9. private final long twepoch = 1420041600000L;
  10. /** 机器id所占的位数 */
  11. private final long workerIdBits = 5L;
  12. /** 数据标识id所占的位数 */
  13. private final long datacenterIdBits = 5L;
  14. /** 支持的最大机器id,结果是31 (这个移位算法可以很快的计算出几位二进制数所能表示的最大十进制数) */
  15. private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
  16. /** 支持的最大数据标识id,结果是31 */
  17. private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
  18. /** 序列在id中占的位数 */
  19. private final long sequenceBits = 12L;
  20. /** 机器ID向左移12位 */
  21. private final long workerIdShift = sequenceBits;
  22. /** 数据标识id向左移17位(12+5) */
  23. private final long datacenterIdShift = sequenceBits + workerIdBits;
  24. /** 时间截向左移22位(5+5+12) */
  25. private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
  26. /** 生成序列的掩码,这里为4095 (0b111111111111=0xfff=4095) */
  27. private final long sequenceMask = -1L ^ (-1L << sequenceBits);
  28. /** 工作机器ID(0~31) */
  29. private long workerId;
  30. /** 数据中心ID(0~31) */
  31. private long datacenterId;
  32. /** 毫秒内序列(0~4095) */
  33. private long sequence = 0L;
  34. /** 上次生成ID的时间截 */
  35. private long lastTimestamp = -1L;
  36. /**
  37. * 构造函数
  38. * @param workerId 工作ID (0~31)
  39. * @param datacenterId 数据中心ID (0~31)
  40. */
  41. public SnowflakeIdWorker(long workerId, long datacenterId) {
  42. if (workerId > maxWorkerId || workerId < 0) {
  43. throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
  44. }
  45. if (datacenterId > maxDatacenterId || datacenterId < 0) {
  46. throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
  47. }
  48. this.workerId = workerId;
  49. this.datacenterId = datacenterId;
  50. }
  51. /**
  52. * 获得下一个ID (该方法是线程安全的)
  53. * @return SnowflakeId
  54. */
  55. public synchronized long nextId() {
  56. long timestamp = timeGen();
  57. //如果当前时间小于上一次ID生成的时间戳,说明系统时钟回退过这个时候应当抛出异常
  58. if (timestamp < lastTimestamp) {
  59. throw new RuntimeException(
  60. String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
  61. }
  62. //如果是同一时间生成的,则进行毫秒内序列
  63. if (lastTimestamp == timestamp) {
  64. sequence = (sequence + 1) & sequenceMask;
  65. //毫秒内序列溢出
  66. if (sequence == 0) {
  67. //阻塞到下一个毫秒,获得新的时间戳
  68. timestamp = tilNextMillis(lastTimestamp);
  69. }
  70. }
  71. //时间戳改变,毫秒内序列重置
  72. else {
  73. sequence = 0L;
  74. }
  75. //上次生成ID的时间截
  76. lastTimestamp = timestamp;
  77. //移位并通过或运算拼到一起组成64位的ID
  78. return ((timestamp - twepoch) << timestampLeftShift) //
  79. | (datacenterId << datacenterIdShift) //
  80. | (workerId << workerIdShift) //
  81. | sequence;
  82. }
  83. /**
  84. * 阻塞到下一个毫秒,直到获得新的时间戳
  85. * @param lastTimestamp 上次生成ID的时间截
  86. * @return 当前时间戳
  87. */
  88. protected long tilNextMillis(long lastTimestamp) {
  89. long timestamp = timeGen();
  90. while (timestamp <= lastTimestamp) {
  91. timestamp = timeGen();
  92. }
  93. return timestamp;
  94. }
  95. /**
  96. * 返回以毫秒为单位的当前时间
  97. * @return 当前时间(毫秒)
  98. */
  99. protected long timeGen() {
  100. return System.currentTimeMillis();
  101. }
  102. }

参考文档

Twitter的分布式自增ID算法snowflake - C#版 雪花算法-全局唯一ID生成器 关于全局ID,雪花(snowflake)算法的说明 https://github.com/dunitian/snowflake-net