美文网首页
MongoDB ObjectId 源码剖析

MongoDB ObjectId 源码剖析

作者: 七秒钟回忆待续 | 来源:发表于2021-07-27 15:29 被阅读0次

    官方对 ObjectId 的描述:https://docs.mongodb.com/manual/reference/method/ObjectId/#objectid

    • a 4-byte timestamp value, representing the ObjectId's creation, measured in seconds since the Unix epoch
    • a 5-byte random value
    • a 3-byte incrementing counter, initialized to a random value

    Golang 使用的客户端为 https://github.com/mongodb/mongo-go-driver ,此文章使用的版本 v1.7.0

    源码为 go.mongodb.org/mongo-driver@v1.7.0/bson/primitive/objectid.go

    func NewObjectID() ObjectID {
        return NewObjectIDFromTimestamp(time.Now())
    }
    
    // NewObjectIDFromTimestamp generates a new ObjectID based on the given time.
    func NewObjectIDFromTimestamp(timestamp time.Time) ObjectID {
        var b [12]byte // 12个字节
        binary.BigEndian.PutUint32(b[0:4], uint32(timestamp.Unix())) // 前4个字节为时间戳
        copy(b[4:9], processUnique[:]) // "不变的"5字节随机数
        putUint24(b[9:12], atomic.AddUint32(&objectIDCounter, 1)) // 动态变化的"不变的"3字节随机数+1
        return b
    }
    

    随机数就是预料之中的 /dev/urandom ,Go相关代码为 go/src/crypto/rand/rand_unix.go

    相关文章

      网友评论

          本文标题:MongoDB ObjectId 源码剖析

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