美文网首页Golang
nsq源码(7) nsqd messageID

nsq源码(7) nsqd messageID

作者: Linrundong | 来源:发表于2019-01-22 13:38 被阅读1次

messageID 消息唯一标识

  • GenerateID()返回ID
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()
}
  • NewGUID()生成ID
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
}

相关文章

网友评论

    本文标题:nsq源码(7) nsqd messageID

    本文链接:https://www.haomeiwen.com/subject/gcpljqtx.html