雪花算法是一种用于生成全局唯一ID的算法,最初由Twitter开发,用于解决分布式系统中生成ID的问题。其核心思想是将一个64位的长整型ID划分成多个部分,每个部分用于表示不同的信息,确保了生成的ID在分布式环境下的唯一性。
package mainimport ( "fmt" "sync" "time")const ( workerBits = 10 sequenceBits = 12 workerMax = -1 ^ (-1 << workerBits) sequenceMask = -1 ^ (-1 << sequenceBits) timeShift = workerBits + sequenceBits workerShift = sequenceBits epoch = 1609459200000)type Snowflake struct { mu sync.Mutex lastTime int64 workerID int64 sequence int64}func NewSnowflake(workerID int64) *Snowflake { if workerID < 0 || workerID > workerMax { panic(fmt.Sprintf("worker ID must be between 0 and %d", workerMax)) } return &Snowflake{ lastTime: time.Now().UnixNano() / 1e6, workerID: workerID, sequence: 0, }}func (sf *Snowflake) NextID() int64 { sf.mu.Lock() defer sf.mu.Unlock() currentTime := time.Now().UnixNano() / 1e6 if currentTime < sf.lastTime { panic(fmt.Sprintf("clock moved backwards, refusing to generate ID for %d milliseconds", sf.lastTime-currentTime)) } if currentTime == sf.lastTime { sf.sequence = (sf.sequence + 1) & sequenceMask if sf.sequence == 0 { for currentTime <= sf.lastTime { currentTime = time.Now().UnixNano() / 1e6 } } } else { sf.sequence = 0 } sf.lastTime = currentTime id := (currentTime-epoch)<<timeShift | (sf.workerID << workerShift) | sf.sequence return id}func main() { sf := NewSnowflake(1) // 假设工作节点ID为1 for i := 0; i < 10; i++ { id := sf.NextID() fmt.Println(id) time.Sleep(time.Millisecond) }}
在高并发场景下,保障雪花算法生成的ID唯一性和递增性的关键在于:
总体来说,雪花算法在高并发下是一个可靠的ID生成方案。它的高性能和低碰撞概率使得它在分布式系统中被广泛应用。
本文链接:http://www.28at.com/showinfo-26-43328-0.html聊一聊雪花算法与分布式ID生成
声明:本网页内容旨在传播知识,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。邮件:2376512515@qq.com
上一篇: 深入解析HTML的<a>标签