52 lines
1.1 KiB
Go
52 lines
1.1 KiB
Go
package q5
|
|
|
|
import (
|
|
"fmt"
|
|
"time"
|
|
)
|
|
|
|
const Q5_EPOCH = 1419120000000
|
|
|
|
const MACHINE_ID_BIT_NUM = 12
|
|
const SEQUNCE_ID_BIT_NUM = 10
|
|
const MAX_MACHINE_ID = (1 << MACHINE_ID_BIT_NUM) - 1
|
|
const MAX_SEQUNCE_ID = (1 << SEQUNCE_ID_BIT_NUM) - 1
|
|
|
|
type Uuid struct {
|
|
machineId int32
|
|
sequenceId int32
|
|
lastGenerateTick int64
|
|
}
|
|
|
|
func (this *Uuid) Generate() int64 {
|
|
var value int64
|
|
tick := GetTickCount()
|
|
if tick == this.lastGenerateTick {
|
|
this.sequenceId++
|
|
if this.sequenceId >= MAX_SEQUNCE_ID {
|
|
for tick <= this.lastGenerateTick {
|
|
time.Sleep(time.Millisecond * 1)
|
|
tick = GetTickCount()
|
|
}
|
|
this.sequenceId = 0
|
|
}
|
|
} else {
|
|
this.sequenceId = 0
|
|
}
|
|
this.lastGenerateTick = tick
|
|
// 保留后41位时间
|
|
value = (tick - Q5_EPOCH) << 22
|
|
//中间12位是机器ID
|
|
value |= int64((int64(this.machineId) & int64(MAX_MACHINE_ID)) << SEQUNCE_ID_BIT_NUM)
|
|
//最后10位是sequenceID
|
|
value |= int64(this.sequenceId & MAX_SEQUNCE_ID)
|
|
return value
|
|
}
|
|
|
|
func (this *Uuid) SetMachineId(macId int32) {
|
|
if macId > MAX_MACHINE_ID || macId < 1 {
|
|
panic(fmt.Sprintf("Uuid.SetMachineId error %d", macId))
|
|
}
|
|
this.machineId = macId
|
|
}
|