Snowflake algorithm
Snowflake is the open-source distributed ID generation algorithm for Twitter, and the result is a long ID. The core idea is: use 41bit as the number of milliseconds, 10bit as the machine ID (5 bit is the data center, 5 bit Machine ID), 12bit as the number of milliseconds (meaning that each node can produce 4,096 IDs per millisecond), and finally a sign bit, is always 0.
I've just seen a discussion of Snowflake's article, and I've seen some of the algorithms that introduce distributed ID generation. But it has not been implemented in C #. This time the code is basically translated into the Java code in that article
The core code is as follows
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位的IDreturn ((timestamp - Twepoch) << _timestampLeftShift) | (DataCenterId << _datacenterIdShift) | (WorkerId << _workerIdShift) | _sequence;
Because the syntax of C # and Java is still more like, the code is almost copy-and-paste. For more discussion please see the above article.
GitHub
Snowflake distributed Unique ID C # implementation