go - 多个 goroutine 中的命名空间 uuid

标签 go uuid rfc4122

我想用 go 语言为高度可扩展的应用程序创建一个“无冲突”的唯一 ID。

维基百科推荐 UUID 的命名空间变体(我只能假设指的是版本 3 或 5) Wikipedia具体说明:

Where unique identifiers are required for distributed applications, so that UUIDs do not clash even when data from many devices is merged, the randomness of the seeds and generators used on every device must be reliable for the life of the application. Where this is not feasible, RFC4122 recommends using a namespace variant instead.

我遇到了一些困难

  1. 版本 3 和 5 需要散列数据,由于以下原因,这似乎是不必要的事情:

    1.1。我的应用程序可能使用相同的数据(我想要不同的 ID)

    1.2。我假设在数据泄漏方面,内部 random() 熵被认为是安全的我不明白为什么需要加密散列(因为我猜散列比一些种子计算需要更多的资源)。

  2. 命名空间应该是一个值,可以防止在高并发环境中可能出现的冲突。在 GO 中,goroutine 可以并行运行,并且由于服务器性能高(如维基百科所述),可能会使用相同的种子。我假设命名空间的最佳值是 goroutine 的 id,因此可以避免在同一台机器上发生冲突。我找不到任何正确的方法来检索当前 goroutine 执行的唯一 ID。

  3. 如果 wikipedia 实际上恢复到带有 namespace 组件的版本 4(随机),我该如何生成这样的 guid? docs不显示这种选项

长话短说: 我如何在 GOLang 中正确安全且可扩展地生成唯一 ID?

最佳答案

文档指出:func NewRandom() - 返回随机(版本 4)UUID 或 panic 。 UUID 的强度基于 crypto/rand 包的强度。

这意味着此包使用 crypto/rand 密码强度随机生成类型 4 uuid。就个人而言,只要实现中没有错误,我相信除非我每天生成数十亿个 ID。

另一种选择是使用版本 5:func NewSHA1(space UUID, data []byte) UUID,并为其提供 Vesion 1 UUID 作为命名空间,以及来自 crypto/random 的数据作为“数据”。即像这样的东西:

// this is a static namespace for this machine, say
var namespace = uuid.NewUUID()


// generate a random UUID with the global namespace
func NewNamespacedRandom() (uuid.UUID, error) {

    // read 16 crypto-random bytes
    rnd := make([]byte, 16)
    if _, err := rand.Read(rnd); err != nil {
        return nil, err
    }

    return uuid.NewSHA1(namespace, rnd), nil
}

func main() {

    u, err := NewNamespacedRandom()
    if err != nil {
        panic(err)
    }
    fmt.Println(u)

}

关于go - 多个 goroutine 中的命名空间 uuid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27592074/

相关文章:

ios - 我们在 iOS 上有哪个唯一设备标识符在安装/删除/重新安装应用程序时不会改变

postgresql - 如何在 postgresql 中对 UUID 进行键盘分页?

mongodb - 大型分布式系统中 ObjectId 与 UUID 的冲突概率

go - 使用 Gin 框架验证 Golang 中的枚举

unit-testing - 使用 Go 语言进行测试的正确包命名

function - 去旅游 #18 : understanding pic. 秀

go - 使用go mod时出现 'ambiguous import'怎么解决?

javascript - 类型错误:无法读取未定义的属性 'v4'