You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
38 lines
719 B
38 lines
719 B
package snowflake
|
|
|
|
import (
|
|
"errors"
|
|
"time"
|
|
)
|
|
|
|
//雪花算法
|
|
func NewWorker(workerId int64) (*Worker, error) {
|
|
if workerId < 0 || workerId > workerMax {
|
|
return nil, errors.New("工作机器的ID超出范围!")
|
|
}
|
|
// 生成一个新节点
|
|
return &Worker{
|
|
timestamp: 0,
|
|
workerId: workerId,
|
|
number: 0,
|
|
}, nil
|
|
}
|
|
|
|
func (w *Worker) GetId() int64 {
|
|
w.mu.Lock()
|
|
defer w.mu.Unlock()
|
|
now := time.Now().UnixNano() / 1e6
|
|
if w.timestamp == now {
|
|
w.number++
|
|
if w.number > numberMax {
|
|
for now <= w.timestamp {
|
|
now = time.Now().UnixNano() / 1e6
|
|
}
|
|
}
|
|
} else {
|
|
w.number = 0
|
|
w.timestamp = now
|
|
}
|
|
ID := int64((now-startTime)<<timeShift | (w.workerId << workerShift) | (w.number))
|
|
return ID
|
|
}
|
|
|