1
0
mirror of https://github.com/charlienet/go-mixed.git synced 2025-07-18 00:22:41 +08:00

snow flake

This commit is contained in:
2022-06-22 10:45:00 +08:00
parent 1eeed34adf
commit ed9a684933
2 changed files with 67 additions and 0 deletions

57
snow_flake/snow_flake.go Normal file
View File

@ -0,0 +1,57 @@
package snowflake
import (
"sync"
"time"
)
// 雪花算法默认起始时间 2020-01-01
const defaultStarTimestamp = 1579536000
const (
MachineIdBits = uint(8) //机器id所占的位数
SequenceBits = uint(12) //序列所占的位数
//MachineIdMax = int64(-1 ^ (-1 << MachineIdBits)) //支持的最大机器id数量
SequenceMask = int64(-1 ^ (-1 << SequenceBits)) //
MachineIdShift = SequenceBits //机器id左移位数
TimestampShift = SequenceBits + MachineIdBits //时间戳左移位数
)
type SnowFlake interface {
GetId() int64
}
type snowflake struct {
sync.Mutex
startTimeStamp int64
timestamp int64
machineId int64
sequence int64
}
func CreateSnowflake(machineId int64) SnowFlake {
return &snowflake{
startTimeStamp: defaultStarTimestamp,
machineId: machineId,
}
}
func (s *snowflake) GetId() int64 {
s.Lock()
defer s.Unlock()
now := time.Now().UnixNano() / 1e6
if s.timestamp == now {
s.sequence = (s.sequence + 1) & SequenceMask
if s.sequence == 0 {
for now <= s.timestamp {
now = time.Now().UnixNano() / 1e6
}
}
} else {
s.sequence = 0
}
s.timestamp = now
r := (now-s.startTimeStamp)<<TimestampShift | (s.machineId << MachineIdShift) | (s.sequence)
return r
}

View File

@ -0,0 +1,10 @@
package snowflake
import "testing"
func TestGetId(t *testing.T) {
s := CreateSnowflake(22)
for i := 0; i < 100; i++ {
t.Log(s.GetId())
}
}