1 Star 0 Fork 0

LRY / go-utils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
worker.go 2.01 KB
一键复制 编辑 原始数据 按行查看 历史
李瑞阳 提交于 2021-05-21 17:34 . Initial commit
// coding: utf-8
// @Author : lryself
// @Date : 2021/5/13 1:29
// @Software: GoLand
package snowflake
import (
"errors"
"sync"
"time"
)
const (
workerIDBits = uint64(5) // 10bit 工作机器ID中的 5bit workerID
dataCenterIDBits = uint64(5) // 10 bit 工作机器ID中的 5bit dataCenterID
sequenceBits = uint64(12)
maxWorkerID = int64(-1) ^ (int64(-1) << workerIDBits) //节点ID的最大值 用于防止溢出
maxDataCenterID = int64(-1) ^ (int64(-1) << dataCenterIDBits)
maxSequence = int64(-1) ^ (int64(-1) << sequenceBits)
timeLeft = uint8(22) // timeLeft = workerIDBits + sequenceBits // 时间戳向左偏移量
dataLeft = uint8(17) // dataLeft = dataCenterIDBits + sequenceBits
workLeft = uint8(12) // workLeft = sequenceBits // 节点IDx向左偏移量
// 2020-05-20 08:00:00 +0800 CST
epoch = int64(1589923200000) // 常量时间戳(毫秒)
)
type Worker struct {
mu sync.Mutex
LastStamp int64 // 记录上一次ID的时间戳
WorkerID int64 // 该节点的ID
DataCenterID int64 // 该节点的 数据中心ID
Sequence int64 // 当前毫秒已经生成的ID序列号(从0 开始累加) 1毫秒内最多生成4096个ID
}
func (w *Worker) getMilliSeconds() int64 {
return time.Now().UnixNano() / 1e6
}
func (w *Worker) NextID() (uint64,error) {
w.mu.Lock()
defer w.mu.Unlock()
return w.nextID()
}
func (w *Worker) nextID() (uint64,error) {
timeStamp := w.getMilliSeconds()
if timeStamp < w.LastStamp{
return 0,errors.New("time is moving backwards,waiting until")
}
if w.LastStamp == timeStamp{
w.Sequence = (w.Sequence + 1) & maxSequence
if w.Sequence == 0 {
for timeStamp <= w.LastStamp {
timeStamp = w.getMilliSeconds()
}
}
}else {
w.Sequence = 0
}
w.LastStamp = timeStamp
id := ((timeStamp - epoch) << timeLeft) |
(w.DataCenterID << dataLeft) |
(w.WorkerID << workLeft) |
w.Sequence
return uint64(id),nil
}
func NewWorker(workerID,dataCenterID int64) *Worker {
return &Worker{
WorkerID: workerID,
LastStamp: 0,
Sequence: 0,
DataCenterID: dataCenterID,
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/lryself/go-utils.git
git@gitee.com:lryself/go-utils.git
lryself
go-utils
go-utils
v0.0.5

搜索帮助

344bd9b3 5694891 D2dac590 5694891