C # implements Snowflake algorithm ID generation

Source: Internet
Author: User

http://blog.csdn.net/w200221626/article/details/52064976

C # implements Snowflake algorithm

    // <summary>    /// dynamic production of a regular ID    // </summary>     Public classSnowflake {Private Static LongMachineID;//Machine ID        Private Static LongDatacenterid = 0L;//Data ID        Private Static Longsequence = 0L;//counting starts from zero    Private Static LongTwepoch = 687888001020L;//Unique time random amount    Private Static LongMachineidbits = 5L;//Machine code bytes        Private Static LongDatacenteridbits = 5L;//bytes of data         Public Static LongMaxmachineid = -1l ^ -1l << (int) Machineidbits;//MAX Machine ID        Private Static LongMaxdatacenterid = -1l ^ ( -1l << (int) datacenteridbits);//MAX Data ID    Private Static LongSequencebits = 12L;//Counter bytes, 12 bytes to save the digital count    Private Static LongMachineidshift = sequencebits;//Machine code data left shift number, that is, the number of bits occupied by the back counter        Private Static LongDatacenteridshift = sequencebits + machineidbits;Private Static LongTimestampleftshift = sequencebits + machineidbits + datacenteridbits;//Timestamp left move bit is machine code + counter Total bytes + data byte number         Public Static LongSequencemask = -1l ^ -1l << (int) Sequencebits;//A microsecond can generate a count, if this value is reached until the next subtle in the generation    Private Static LongLasttimestamp = -1l;//Last time stamp        Private Static ObjectSyncRoot =New Object();//Locking Object        StaticSnowflake Snowflake; Public StaticSnowflake Instance () {if(Snowflake = =NULL) Snowflake =NewSnowflake ();returnSnowflake; } PublicSnowflake () {Snowflakes (0L,-1); } PublicSnowflake (LongMachineID) {Snowflakes (MachineID,-1); } PublicSnowflake (LongMachineID,LongDatacenterid) {Snowflakes (MachineID, Datacenterid); }Private voidSnowflakes (LongMachineID,LongDatacenterid) {if(MachineID >= 0) {if(MachineID > Maxmachineid) {Throw NewException ("Illegal machine code ID");            } Snowflake.machineid = MachineID; }if(Datacenterid >= 0) {if(Datacenterid > Maxdatacenterid) {Throw NewException ("Data center ID is illegal");            } Snowflake.datacenterid = Datacenterid; }        }// <summary>        // Generate current timestamp        // </summary>        // <returns> milliseconds </returns>        Private Static LongGettimestamp () {return(Long) (Datetime.utcnow-NewDateTime (1970, 1, 1, 0, 0, 0, DATETIMEKIND.UTC)).        TotalMilliseconds; }// <summary>        /// Get next microsecond timestamp        // </summary>        /// <param name= "Lasttimestamp" ></param>        // <returns></returns>        Private Static LongGetnexttimestamp (LongLasttimestamp) {Longtimestamp = Gettimestamp ();if(Timestamp <= Lasttimestamp)            {timestamp = Gettimestamp (); }returnTimestamp }// <summary>        /// Get ID of long shaping        // </summary>        // <returns></returns>         Public LongGetId () {Lock(SyncRoot) {Longtimestamp = Gettimestamp ();if(Snowflake.lasttimestamp = = timestamp) {//The same subtle generation IDSequence = (sequence + 1) & Sequencemask;//Use the & operation to calculate whether the count generated in that Microsecond has reached the upper limit                    if(sequence = = 0) {//A subtle inside generated ID count has reached the upper limit, waiting for the next subtletimestamp = Getnexttimestamp (Snowflake.lasttimestamp); }                }Else{//different microsecond generation IDsequence = 0L; }if(Timestamp < Lasttimestamp) {Throw NewException ("The timestamp is smaller than the last time the ID was generated, so the exception"); } Snowflake.lasttimestamp = timestamp;//Save the current timestamp as the timestamp of the last build ID                LongId = ((Timestamp-twepoch) << (int) timestampleftshift) | (Datacenterid << (int) datacenteridshift) | (MachineID << (int) machineidshift) | SequencereturnId; }        }

C # implements Snowflake algorithm ID generation

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.