123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147 |
- package util
- import (
- "errors"
- "fmt"
- "github.com/spf13/viper"
- "sync"
- "time"
- )
- type SnowFlakeIdWorker struct {
-
- twepoch int64
-
- workerIdBits int64
-
- dataCenterIdBits int64
-
- maxWorkerId int64
-
- maxDataCenterId int64
-
- sequenceBits int64
-
- workerIdShift int64
-
- dataCenterIdShift int64
-
- timestampLeftShift int64
-
- sequenceMask int64
-
- workerId int64
-
- dataCenterId int64
-
- sequence int64
-
- lastTimestamp int64
-
- lock sync.Mutex
- }
- func (p *SnowFlakeIdWorker) init(dataCenterId int64, workerId int64) {
- t, _ := time.Parse("2006-01-02", viper.GetString("time.time"))
-
- p.twepoch = t.Unix()
-
- p.workerIdBits = 5
-
- p.dataCenterIdBits = 5
-
- p.maxWorkerId = -1 ^ (-1 << p.workerIdBits)
-
- p.maxDataCenterId = -1 ^ (-1 << p.dataCenterIdBits)
-
- p.sequenceBits = 12
-
- p.workerIdShift = p.sequenceBits
-
- p.dataCenterIdShift = p.sequenceBits + p.workerIdBits
-
- p.timestampLeftShift = p.sequenceBits + p.workerIdBits + p.dataCenterIdBits
-
- p.sequenceMask = -1 ^ (-1 << p.sequenceBits)
- if workerId > p.maxWorkerId || workerId < 0 {
- panic(errors.New(fmt.Sprintf("Worker ID can't be greater than %d or less than 0", p.maxWorkerId)))
- }
- if dataCenterId > p.maxDataCenterId || dataCenterId < 0 {
- panic(errors.New(fmt.Sprintf("DataCenter ID can't be greater than %d or less than 0", p.maxDataCenterId)))
- }
- p.workerId = workerId
- p.dataCenterId = dataCenterId
-
- p.sequence = 0
-
- p.lastTimestamp = -1
- }
- func (p *SnowFlakeIdWorker) nextId() int64 {
- p.lock.Lock()
- defer p.lock.Unlock()
- timestamp := p.timeGen()
-
- if timestamp < p.lastTimestamp {
- panic(errors.New(fmt.Sprintf("Clock moved backwards. Refusing to generate id for %d milliseconds", p.lastTimestamp-timestamp)))
- }
- if p.lastTimestamp == timestamp {
-
- p.sequence = (p.sequence + 1) & p.sequenceMask
-
- if p.sequence == 0 {
-
- timestamp = p.tilNextMillis(p.lastTimestamp)
- }
- } else {
-
- p.sequence = 0
- }
-
- p.lastTimestamp = timestamp
-
- return ((timestamp - p.twepoch) << p.timestampLeftShift) |
- (p.dataCenterId << p.dataCenterIdShift) |
- (p.workerId << p.workerIdShift) | p.sequence
- }
- func (p *SnowFlakeIdWorker) tilNextMillis(lastTimestamp int64) int64 {
- timestamp := p.timeGen()
- for timestamp <= lastTimestamp {
- timestamp = p.timeGen()
- }
- return timestamp
- }
- func (p *SnowFlakeIdWorker) timeGen() int64 {
- return time.Now().UnixNano() / 1e6
- }
- func GetID() int64 {
- idWorker := &SnowFlakeIdWorker{}
- idWorker.init(0, 1)
- return idWorker.nextId()
- }
|