Home 类库下载 C# class library c# distributed ID generator

c# distributed ID generator

Nov 04, 2016 pm 04:48 PM
c#

Introduction

This is written based on Twitter's snowflake. Here is the Chinese introduction.

c# distributed ID generator


As shown in the picture above, a 64-bit ID, except for the leftmost sign bit (fixed to 0, To ensure that the generated IDs are all positive), there are still 63 bits available.

The following code is slightly different from the digit allocation in the picture, except that the 10-bit working machine ID in the middle part remains unchanged, and the number of digits in the timestamp and serial number It can be changed according to your own needs, that is to say, you can move the working machine ID in the middle to the left or to the right.

Code

/// <summary>
    /// 64位ID生成器,最高位为符号位,始终为0,可用位数63.
    /// 实例编号占10位,范围为0-1023
    /// 时间戳和索引共占53位
    /// </summary>
    public sealed class IdCreator
    {        long timestamp = 0;//当前时间戳
        long index = 0;//索引/计数器
        long instanceID;//实例编号
        int indexBitLength;//索引可用位数
        long tsMax = 0;//时间戳最大值
        long indexMax = 0;        static IdCreator _default = new IdCreator();        /// <summary>
        /// 
        /// </summary>
        /// <param name="instanceID">实例编号(0-1023)</param>
        /// <param name="indexBitLength">索引可用位数(1-32).每秒可生成ID数等于2的indexBitLength次方.大并发情况下,当前秒内ID数达到最大值时,将使用下一秒的时间戳,不影响获取ID.</param>
        /// <param name="initTimestamp">初始化时间戳,精确到秒.当之前同一实例生成ID的timestamp值大于当前时间的时间戳时,
        /// 有可能会产生重复ID(如持续一段时间的大并发请求).设置initTimestamp比最后的时间戳大一些,可避免这种问题</param>
        public IdCreator(int instanceID, int indexBitLength, long? initTimestamp = null)        {            if (instanceID < 0)
            {                //这里给每个实例随机生成个实例编号
                Random r = new Random();                this.instanceID = r.Next(0, 1024);
            }            else
            {                this.instanceID = instanceID % 1024;
            }            if (indexBitLength < 1)
            {                this.indexBitLength = 1;
            }            else if (indexBitLength > 32)            {                this.indexBitLength = 32;
            }            else
            {                this.indexBitLength = indexBitLength;
            }
            tsMax = Convert.ToInt64(new string(&#39;1&#39;, 53 - indexBitLength), 2);
            indexMax = Convert.ToInt64(new string(&#39;1&#39;, indexBitLength), 2);            if (initTimestamp != null)
            {                this.timestamp = initTimestamp.Value;
            }
        }        /// <summary>
        /// 默认每实例每秒生成65536个ID,从1970年1月1日起,累计可使用4358年
        /// </summary>
        /// <param name="instanceID">实例编号(0-1023)</param>
        public IdCreator(int instanceID) : this(instanceID, 16)        {

        }        /// <summary>
        /// 默认每秒生成65536个ID,从1970年1月1日起,累计可使用4358年
        /// </summary>
        public IdCreator() : this(-1)        {

        }        /// <summary>
        /// 生成64位ID
        /// </summary>
        /// <returns></returns>
        public long Create()        {            long id = 0;            lock (this)
            {                //增加时间戳部分
                long ts = Harry.Common.Utils.GetTimeStamp() / 1000;

                ts = ts % tsMax;  //如果超过时间戳允许的最大值,从0开始
                id = ts << (10 + indexBitLength);//腾出后面部分,给实例编号和缩引编号使用

                //增加实例部分
                id = id | (instanceID << indexBitLength);                //获取计数
                if (timestamp < ts)
                {
                    timestamp = ts;
                    index = 0;
                }                else
                {                    if (index > indexMax)
                    {
                        timestamp++;
                        index = 0;
                    }
                }

                id = id | index;

                index++;
            }            return id;
        }        /// <summary>
        /// 获取当前实例的时间戳
        /// </summary>
        public long CurrentTimestamp
        {            get
            {                return this.timestamp;
            }
        }        /// <summary>
        /// 默认每实例每秒生成65536个ID,从1970年1月1日起,累计可使用4358年
        /// </summary>
        public static IdCreator Default
        {            get
            {                return _default;
            }
        }
    }
Copy after login

Code description

When using it, you need a new IdCreator instance, and then call the Create() method to generate an ID number. The instance of IdCreator needs to be assigned to a static variable to ensure the uniqueness of the ID number. If it is a distributed deployment, the instanceID parameter needs to be passed to the constructor of IdCreator , each deployment must have a different value, ranging from 0-1023. The indexBitLength parameter in the constructor represents the length of the 'serial number' on the far right in the figure, which is no longer fixed to 12bit, and ranges from 1- 32. The remaining available bits are left for the timestamp.

Note: The timestamp of the IdCreator class is measured in seconds. If you want to change it to milliseconds, you only need to change the code long ts = Harry.Common.Utils.GetTimeStamp () / 1000; change to long ts = Harry.Common.Utils.GetTimeStamp(); and that’s it.

Sample code

 IdCreator c=new IdCreator(0,16); 
  var id=c.Create();
Copy after login

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Active Directory with C# Active Directory with C# Sep 03, 2024 pm 03:33 PM

Guide to Active Directory with C#. Here we discuss the introduction and how Active Directory works in C# along with the syntax and example.

Random Number Generator in C# Random Number Generator in C# Sep 03, 2024 pm 03:34 PM

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

C# Serialization C# Serialization Sep 03, 2024 pm 03:30 PM

Guide to C# Serialization. Here we discuss the introduction, steps of C# serialization object, working, and example respectively.

C# Data Grid View C# Data Grid View Sep 03, 2024 pm 03:32 PM

Guide to C# Data Grid View. Here we discuss the examples of how a data grid view can be loaded and exported from the SQL database or an excel file.

Prime Numbers in C# Prime Numbers in C# Sep 03, 2024 pm 03:35 PM

Guide to Prime Numbers in C#. Here we discuss the introduction and examples of prime numbers in c# along with code implementation.

Patterns in C# Patterns in C# Sep 03, 2024 pm 03:33 PM

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

Factorial in C# Factorial in C# Sep 03, 2024 pm 03:34 PM

Guide to Factorial in C#. Here we discuss the introduction to factorial in c# along with different examples and code implementation.

The difference between multithreading and asynchronous c# The difference between multithreading and asynchronous c# Apr 03, 2025 pm 02:57 PM

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

See all articles