刚刚看到一篇讨论snowflake的文章

时间:2022-06-07 05:12:09

snowflake是Twitter开源的漫衍式ID生成算法,功效是一个long型的ID。其核心思想是:使用41bit作为毫秒数,,10bit作为机器的ID(5个bit是数据中心,5个bit的机器ID),12bit作为毫秒内的流水号(意味着每个节点在每毫秒可以孕育产生 4096 个 ID),最后还有一个标记位,永远是0。

刚刚看到一篇讨论snowflake的文章,之前也看过一些介绍漫衍式ID生成的算法.但是一直没有用c#实现过.此次正好实现以下.代码的话根基上是翻译了一下那篇文章里的java代码

核心代码如下

var timestamp = TimeGen(); //如果当前时间小于上一次ID生成的时间戳,说明系统时钟回退过这个时候该当抛出异常 if (timestamp < _lastTimestamp) { throw new Exception($"Clock moved backwards. Refusing to generate id for {_lastTimestamp - timestamp} milliseconds"); } //如果是同一时间生成的,则进行毫秒内序列 if (_lastTimestamp == timestamp) { _sequence = (_sequence + 1) & _sequenceMask; //毫秒内序列溢出 if (_sequence == 0) { //梗阻到下一个毫秒,获得新的时间戳 timestamp = TilNextMillis(_lastTimestamp); } } //时间戳转变,毫秒内序列重置 else { _sequence = 0L; } //上次生成ID的时间截 _lastTimestamp = timestamp; //移位并通过或运算拼到一起构成64位的ID return ((timestamp - Twepoch) << _timestampLeftShift) | (DataCenterId << _datacenterIdShift) | (WorkerId << _workerIdShift) | _sequence;

由于c#和java的语法还是对照像的,代码几乎就是复制粘贴.更多的讨论请看上面的文章.