Snowflake distributed Unique ID C # implementation

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.