为什么 mongodb java 驱动程序在 ObjectId 中使用随机字节而不是机器 ID?

Why mongodb java driver uses random bytes instead of machine id in ObjectId?

很多人说ObjectId包括:

如果 objectId 包含所有这些元素,则可以保证所有 ID 在集群中都是唯一的。但是文档说没有机器和进程 ID,objectId 只包含一个随机值 (https://docs.mongodb.com/manual/reference/method/ObjectId)

我查看了 java mongo 驱动程序 ObjectId 生成并找到了证据:

SecureRandom secureRandom = new SecureRandom();
RANDOM_VALUE1 = secureRandom.nextInt(0x01000000);
RANDOM_VALUE2 = (short) secureRandom.nextInt(0x00008000);

// ...

private ObjectId(final int timestamp, final int counter, final boolean checkCounter) {
    this(timestamp, RANDOM_VALUE1, RANDOM_VALUE2, counter, checkCounter);
}

因此,有可能(好吧,概率确实很低,但仍然如此)两台机器生成相同的随机数,并且所有因此生成的 id 很可能会发生冲突。为什么做出这样的决定?它仍然是完全独特的,但我不明白什么吗? 谢谢!

编辑: 嗯,问题的目的是:我应该自己实现MAC地址和processId的检索并生成ObjectId还是随机留下5个字节数,因为没有区别?

Why mongodb java driver uses random bytes instead of machine id in ObjectId?

这种行为是mandated by the ObjectId specification

同一文档提供the rationale:

Random Value: Originally, this field consisted of the Machine ID and Process ID fields. There were numerous divergences between drivers due to implementation choices, and the Machine ID field traditionally used the MD5 hashing algorithm which can't be used on FIPS compliant machines. In order to allow for a similar behaviour among all drivers and the MongoDB Server, these two fields have been collated together into a single 5-byte random value, unique to a machine and process.

您不需要实现 ObjectId 生成,因为所有 MongoDB 驱动程序都必须提供此功能。