github.com/duomi520/utils@v0.0.0-20240430123446-e03a4cddd6ec/snowflake.go (about) 1 package utils 2 3 import ( 4 "sync/atomic" 5 "time" 6 ) 7 8 // 定义魔改版雪花算法的参数 9 // highest 1 bit: always 0 10 // next 10 bit: workerId 11 // next 41 bit: timestamp 12 // lowest 12 bit: sequence 13 const ( 14 //最大1023 15 MaxWorkNumber = 1023 16 WorkLeftShift = uint(12 + 41) 17 TimestampLeftShift = uint(12) 18 ) 19 20 // SnowFlakeIDPlus 魔改版雪花算法,缺失原算法包含的时间戳信息 21 type SnowFlakeIDPlus struct { 22 //时间戳启动计算时间零点 23 systemCenterStartupTime int64 24 //10bit的工作机器id 25 workID int64 26 lastTimestamp int64 27 } 28 29 // NewSnowFlakeIDPlus 新建 30 func NewSnowFlakeIDPlus(id int64, startupTime int64) *SnowFlakeIDPlus { 31 if id < 0 || id >= MaxWorkNumber || startupTime < 0 { 32 return nil 33 } 34 s := &SnowFlakeIDPlus{ 35 systemCenterStartupTime: startupTime, 36 workID: id, 37 lastTimestamp: (id << WorkLeftShift) | ((time.Now().UnixNano()-startupTime)/int64(time.Millisecond))<<TimestampLeftShift, 38 } 39 return s 40 } 41 42 // NextID 取得 id. 43 func (s *SnowFlakeIDPlus) NextID() int64 { 44 return atomic.AddInt64(&s.lastTimestamp, 1) 45 } 46 47 // GetWorkID 根据id计算工作机器id 48 func GetWorkID(id int64) int64 { 49 temp := id >> WorkLeftShift 50 //1111111111 10bit 51 return temp & 1023 52 } 53 54 // GetWorkID 取得工作机器id 55 func (s *SnowFlakeIDPlus) GetWorkID() int64 { 56 return s.workID 57 } 58 59 // 改良版的雪花算法 https://zhuanlan.zhihu.com/p/648460337