【问题标题】:How to generate a unique identifier of a fixed length in Java?如何在Java中生成一个固定长度的唯一标识符?
【发布时间】:2011-07-05 14:39:24
【问题描述】:

我正在尝试生成固定长度的唯一标识符,例如 Megaupload 为上传的文件生成的 ID。

例如:

  • ALGYTAB5
  • BCLD23A6

在此示例中,使用从 A-Z 和 0-9 以及固定长度为 8 的总不同组合为 2,821,109,907,456。

如果生成的 id 之一已被占用怎么办。这些 id 将存储在数据库中,并且不应多次使用。

如何在 Java 中实现这一点?

谢谢。

【问题讨论】:

标签: java uniqueidentifier


【解决方案1】:

嗯...您可以通过以下方式模仿较小的GUID。让你的字符串的前 4 个字节是编码的当前时间 - Unix 之后经过的秒数。最后4个只是随机组合。在这种情况下,两个 ID 一致的唯一方法是它们是同时构建的。由于其他 4 个随机字符,这种可能性非常低。

伪代码:

get current time (4 byte integer
id[0] = 1st byte of current time (encoded to be a digit or a letter)
id[1] = 2nd
id[2] = 3rd
id[3] = 4th
id[4] = random character
id[5] = random character
id[6] = random character
id[7] = random character

【讨论】:

    【解决方案2】:

    我已经尝试过@Armen 的解决方案,但是我想提供另一个解决方案

        UUID idOne = UUID.randomUUID();
    UUID idTwo = UUID.randomUUID();
    UUID idThree = UUID.randomUUID();
    UUID idFour = UUID.randomUUID();
    
    String time = idOne.toString().replace("-", "");
    String time2 = idTwo.toString().replace("-", "");
    String time3 = idThree.toString().replace("-", "");
    String time4 = idFour.toString().replace("-", "");
    
    StringBuffer data = new StringBuffer();
    data.append(time);
    data.append(time2);
    data.append(time3);
    data.append(time4);
    
        SecureRandom random = new SecureRandom();
    int beginIndex = random.nextInt(100);       //Begin index + length of your string < data length
    int endIndex = beginIndex + 10;            //Length of string which you want
    
    String yourID = data.substring(beginIndex, endIndex);
    

    希望对您有所帮助!

    【讨论】:

      【解决方案3】:

      我们正在使用数据库来检查它们是否已经存在。如果 ID 的数量与可能的数量相比较低,那么您应该是相对安全的。

      您还可以查看 UUID 类(尽管它是 16 字节的 UUID)。

      【讨论】:

      【解决方案4】:

      听起来像是hash function 的工作。您不能 100% 保证哈希函数会返回唯一标识符,但它在大多数情况下都有效。哈希冲突必须单独处理,但有许多标准技术可供您研究。

      具体如何处理冲突取决于您使用此唯一标识符的目的。如果它是一个简单的单向标识符,您为程序提供 ID 并返回数据,那么您可以在发生冲突时简单地使用下一个可用的 ID。

      【讨论】:

        【解决方案5】:

        按照以下步骤操作:

        1. generateId()
        2. 通过查询数据库检查是否已经下发。
        3. 如果是,请再次调用 generateId(),直到在 db 中找不到它为止

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-01-16
          • 2010-09-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-12-06
          相关资源
          最近更新 更多