Introduction
This is written based on Twitter's snowflake. Here is the Chinese introduction.
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生成器,最高位為符號(hào)位,始終為0,可用位數(shù)63. /// 實(shí)例編號(hào)占10位,范圍為0-1023 /// 時(shí)間戳和索引共占53位 /// </summary> public sealed class IdCreator { long timestamp = 0;//當(dāng)前時(shí)間戳 long index = 0;//索引/計(jì)數(shù)器 long instanceID;//實(shí)例編號(hào) int indexBitLength;//索引可用位數(shù) long tsMax = 0;//時(shí)間戳最大值 long indexMax = 0; static IdCreator _default = new IdCreator(); /// <summary> /// /// </summary> /// <param name="instanceID">實(shí)例編號(hào)(0-1023)</param> /// <param name="indexBitLength">索引可用位數(shù)(1-32).每秒可生成ID數(shù)等于2的indexBitLength次方.大并發(fā)情況下,當(dāng)前秒內(nèi)ID數(shù)達(dá)到最大值時(shí),將使用下一秒的時(shí)間戳,不影響獲取ID.</param> /// <param name="initTimestamp">初始化時(shí)間戳,精確到秒.當(dāng)之前同一實(shí)例生成ID的timestamp值大于當(dāng)前時(shí)間的時(shí)間戳?xí)r, /// 有可能會(huì)產(chǎn)生重復(fù)ID(如持續(xù)一段時(shí)間的大并發(fā)請(qǐng)求).設(shè)置initTimestamp比最后的時(shí)間戳大一些,可避免這種問題</param> public IdCreator(int instanceID, int indexBitLength, long? initTimestamp = null) { if (instanceID < 0) { //這里給每個(gè)實(shí)例隨機(jī)生成個(gè)實(shí)例編號(hào) 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('1', 53 - indexBitLength), 2); indexMax = Convert.ToInt64(new string('1', indexBitLength), 2); if (initTimestamp != null) { this.timestamp = initTimestamp.Value; } } /// <summary> /// 默認(rèn)每實(shí)例每秒生成65536個(gè)ID,從1970年1月1日起,累計(jì)可使用4358年 /// </summary> /// <param name="instanceID">實(shí)例編號(hào)(0-1023)</param> public IdCreator(int instanceID) : this(instanceID, 16) { } /// <summary> /// 默認(rèn)每秒生成65536個(gè)ID,從1970年1月1日起,累計(jì)可使用4358年 /// </summary> public IdCreator() : this(-1) { } /// <summary> /// 生成64位ID /// </summary> /// <returns></returns> public long Create() { long id = 0; lock (this) { //增加時(shí)間戳部分 long ts = Harry.Common.Utils.GetTimeStamp() / 1000; ts = ts % tsMax; //如果超過時(shí)間戳允許的最大值,從0開始 id = ts << (10 + indexBitLength);//騰出后面部分,給實(shí)例編號(hào)和縮引編號(hào)使用 //增加實(shí)例部分 id = id | (instanceID << indexBitLength); //獲取計(jì)數(shù) if (timestamp < ts) { timestamp = ts; index = 0; } else { if (index > indexMax) { timestamp++; index = 0; } } id = id | index; index++; } return id; } /// <summary> /// 獲取當(dāng)前實(shí)例的時(shí)間戳 /// </summary> public long CurrentTimestamp { get { return this.timestamp; } } /// <summary> /// 默認(rèn)每實(shí)例每秒生成65536個(gè)ID,從1970年1月1日起,累計(jì)可使用4358年 /// </summary> public static IdCreator Default { get { return _default; } } }
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();

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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.

The history and evolution of C# and C are unique, and the future prospects are also different. 1.C was invented by BjarneStroustrup in 1983 to introduce object-oriented programming into the C language. Its evolution process includes multiple standardizations, such as C 11 introducing auto keywords and lambda expressions, C 20 introducing concepts and coroutines, and will focus on performance and system-level programming in the future. 2.C# was released by Microsoft in 2000. Combining the advantages of C and Java, its evolution focuses on simplicity and productivity. For example, C#2.0 introduced generics and C#5.0 introduced asynchronous programming, which will focus on developers' productivity and cloud computing in the future.

There are several ways to modify XML formats: manually editing with a text editor such as Notepad; automatically formatting with online or desktop XML formatting tools such as XMLbeautifier; define conversion rules using XML conversion tools such as XSLT; or parse and operate using programming languages ??such as Python. Be careful when modifying and back up the original files.

Methods to convert XML to JSON include: writing scripts or programs in programming languages ??(such as Python, Java, C#) to convert; pasting or uploading XML data using online tools (such as XML to JSON, Gojko's XML converter, XML online tools) and selecting JSON format output; performing conversion tasks using XML to JSON converters (such as Oxygen XML Editor, Stylus Studio, Altova XMLSpy); converting XML to JSON using XSLT stylesheets; using data integration tools (such as Informatic

C# multi-threaded programming is a technology that allows programs to perform multiple tasks simultaneously. It can improve program efficiency by improving performance, improving responsiveness and implementing parallel processing. While the Thread class provides a way to create threads directly, advanced tools such as Task and async/await can provide safer asynchronous operations and a cleaner code structure. Common challenges in multithreaded programming include deadlocks, race conditions, and resource leakage, which require careful design of threading models and the use of appropriate synchronization mechanisms to avoid these problems.

There are three ways to convert XML to Word: use Microsoft Word, use an XML converter, or use a programming language.

Use most text editors to open XML files; if you need a more intuitive tree display, you can use an XML editor, such as Oxygen XML Editor or XMLSpy; if you process XML data in a program, you need to use a programming language (such as Python) and XML libraries (such as xml.etree.ElementTree) to parse.

How to build applications using .NET? Building applications using .NET can be achieved through the following steps: 1) Understand the basics of .NET, including C# language and cross-platform development support; 2) Learn core concepts such as components and working principles of the .NET ecosystem; 3) Master basic and advanced usage, from simple console applications to complex WebAPIs and database operations; 4) Be familiar with common errors and debugging techniques, such as configuration and database connection issues; 5) Application performance optimization and best practices, such as asynchronous programming and caching.
