Principle of Snowflake Algorithm

principle

The snowflake algorithm is an algorithm used by distributed systems to generate ordered unique IDs by time . The ID generated by the snowflake algorithm is a 64-bit integer number, including a timestamp, machine ID, and serial number. The timestamp is millisecond-level, the machine ID is the ID number of the current server (up to 1024), and the sequence number is the ID generated within the same millisecond (up to 4096 generated within the same millisecond).

  • Timestamps allow IDs to be incremented by time.
  • The machine ID allows each server in the distributed system to not generate the same ID even if they do not communicate.
  • Up to 4096 IDs in 1ms, 4.096 million in 1 second, very efficient.

image.png

Note: The snowflake algorithm relies heavily on the machine time. If there is a problem with the machine time, which leads to a call back, that is, the time is rolled back, then there may be problems with generating IDs and previous duplication.

  • Solution: If the current time is less than the previous time, stop generating the ID.

Code

// MID 机器码
const MID = 11

// lastTimestamp 记录上一个时间戳
var lastTimestamp int64 = 0

// seqN 序列号
var seqN int64 = 0

// Snow 雪花算法
func Snow() (int64, error){
    
    
   timestampMs := time.Now().UnixMilli() << 22
   if timestampMs < lastTimestamp{
    
    
      return 0, errors.New("时钟回拨,生成ID错误")
   }
   if timestampMs != lastTimestamp {
    
    
      seqN = 0
      lastTimestamp = timestampMs
   }
   machineID := int64(MID << 12)
   return timestampMs | machineID | seqN, nil
}

Guess you like

Origin blog.csdn.net/sunningzhzh/article/details/131222072