Ai
3 Star 0 Fork 0

salmon_go/common

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
snowflake.go 2.25 KB
一键复制 编辑 原始数据 按行查看 历史
MikeJia 提交于 2021-03-03 21:08 +08:00 . init
package database
/*
* Snowflake
*
* 1 42 52 64
* +---------------------------------------------------------+--------------+------------------+
* | timestamp(ms) | workerid | sequence |
* +---------------------------------------------------------+--------------+------------------+
* | 0000000000 0000000000 0000000000 0000000000 0 | 0000000000 | 0000000000 00 |
* +-----------------------------------------------+---------+--------------+------------------+
*
* 1. 41位时间截(毫秒级),注意这是时间截的差值(当前时间截 - 开始时间截)。可以使用约70年: (1L << 41) / (1000L * 60 * 60 * 24 * 365) = 69
* 2. 10位数据机器位,可以部署在1024个节点
* 3. 12位序列,毫秒内的计数,同一机器,同一时间截并发4096个序号
*/
import (
"sync"
"time"
)
const (
//开始时间截 (2017-01-01)
twepoch = int64(1483228800000)
//机器id所占的位数
workeridBits = uint(10)
//序列所占的位数
sequenceBits = uint(12)
//支持的最大机器id数量
workeridMax = int64(-1 ^ (-1 << workeridBits))
//
sequenceMask = int64(-1 ^ (-1 << sequenceBits))
//机器id左移位数
workeridShift = sequenceBits
//时间戳左移位数
timestampShift = sequenceBits + workeridBits
)
// A Snowflake struct holds the basic information needed for a snowflake generator worker
type Snowflake struct {
sync.Mutex
timestamp int64
workerid int64
sequence int64
}
// NewSnowflake returns a new snowflake worker that can be used to generate snowflake IDs
func NewSnowflake(workerid int64) *Snowflake {
//if workerid < 0 || workerid > workeridMax {
// return nil, errors.New("workerid must be between 0 and 1023")
//}
return &Snowflake{
timestamp: 0,
workerid: workerid,
sequence: 0,
}
}
// Generate creates and returns a unique snowflake ID
func (s *Snowflake) Generate() int64 {
s.Lock()
now := time.Now().UnixNano() / 1000000
if s.timestamp == now {
s.sequence = (s.sequence + 1) & sequenceMask
if s.sequence == 0 {
for now <= s.timestamp {
now = time.Now().UnixNano() / 1000000
}
}
} else {
s.sequence = 0
}
s.timestamp = now
r := int64((now-twepoch)<<timestampShift | (s.workerid << workeridShift) | (s.sequence))
s.Unlock()
return r
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/salmon-go/common.git
git@gitee.com:salmon-go/common.git
salmon-go
common
common
v0.0.6

搜索帮助