- 推荐学习文档
以下是使用 Go 语言实现雪花算法生成 64 位 ID 的示例代码:
golang">package mainimport ("fmt""sync""time"
)const (// 起始时间戳(2020-01-01)twepoch = 1577836800000workerIDBits = 5datacenterIDBits = 5sequenceBits = 12maxWorkerID = -1 ^ (-1 << workerIDBits)maxDatacenterID = -1 ^ (-1 << datacenterIDBits)maxSequence = -1 ^ (-1 << sequenceBits)workerIDShift = sequenceBitsdatacenterIDShift = sequenceBits + workerIDBitstimestampLeftShift = sequenceBits + workerIDBits + datacenterIDBits
)type Snowflake struct {mu sync.MutexlastTimestamp int64workerID int64datacenterID int64sequence int64
}func NewSnowflake(workerID, datacenterID int64) (*Snowflake, error) {if workerID < 0 || workerID > maxWorkerID {return nil, fmt.Errorf("worker ID must be between 0 and %d", maxWorkerID)}if datacenterID < 0 || datacenterID > maxDatacenterID {return nil, fmt.Errorf("datacenter ID must be between 0 and %d", maxDatacenterID)}return &Snowflake{workerID: workerID,datacenterID: datacenterID,lastTimestamp: -1,sequence: 0,}, nil
}func (s *Snowflake) NextID() int64 {s.mu.Lock()defer s.mu.Unlock()timestamp := time.Now().UnixNano() / 1e6if timestamp < s.lastTimestamp {return 0}if s.lastTimestamp == timestamp {s.sequence = (s.sequence + 1) & maxSequenceif s.sequence == 0 {for timestamp <= s.lastTimestamp {timestamp = time.Now().UnixNano() / 1e6}}} else {s.sequence = 0}s.lastTimestamp = timestampreturn ((timestamp - twepoch) << timestampLeftShift) |(s.datacenterID << datacenterIDShift) |(s.workerID << workerIDShift) |s.sequence
}
你可以使用以下方式调用:
golang">func main() {sf, err := NewSnowflake(1, 1)if err!= nil {panic(err)}id := sf.NextID()fmt.Println(id)
}
这个实现创建了一个雪花算法的结构体Snowflake,通过互斥锁保证并发安全。它根据当前时间戳、工作节点 ID、数据中心 ID 和序列号生成唯一的 64 位 ID。生成的 ID 是一个递增的数字,具有时间顺序性,并且在分布式系统中可以保证唯一性。
希望本文对你有所帮助!如果你有任何问题或建议,欢迎在评论区留言。
关注我看更多有意思的文章哦!👉👉