messageID 消息唯一标识
func (p *protocolV2) PUB(client *clientV2, params [][]byte) ([]byte, error){
msg := NewMessage(topic.GenerateID(), messageBody)
}
// ID生成器
func (t *Topic) GenerateID() MessageID {
retry:
id, err := t.idFactory.NewGUID()
if err != nil {
time.Sleep(time.Millisecond)
goto retry
}
return id.Hex()
}
func (f *guidFactory) NewGUID() (guid, error) {
f.Lock()
// divide by 1048576, giving pseudo-milliseconds, 1ms 约等于 1048576
// 获取当前时间为多少毫秒, 2^20 = 1048576
ts := time.Now().UnixNano() >> 20
// 最新消息时间毫秒数 > 当前,报错
if ts < f.lastTimestamp {
f.Unlock()
return 0, ErrTimeBackwards
}
// 最新消息时间毫秒数 = 当前,根据sequence计数器区分
if f.lastTimestamp == ts {
f.sequence = (f.sequence + 1) & sequenceMask
if f.sequence == 0 {
f.Unlock()
return 0, ErrSequenceExpired
}
} else {
f.sequence = 0
}
f.lastTimestamp = ts
// id = [ 22位ts + 10位 workerId + 12位 sequence ]
id := guid(((ts - twepoch) << timestampShift) |
(f.nodeID << nodeIDShift) |
f.sequence)
if id <= f.lastID {
f.Unlock()
return 0, ErrIDBackwards
}
f.lastID = id
f.Unlock()
return id, nil
}