在保留唯一性的同时缩短 java UUID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20361060/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 01:22:40  来源:igfitidea点击:

Shortening java UUID while preserving the uniqueness

javauuid

提问by Fipil

I'm trying to make the java UUID shorter while preserving the same uniqueness as the UUID has. I wrote the following code:

我试图使 java UUID 更短,同时保留与 UUID 相同的唯一性。我写了以下代码:

public static void main(String[] args) {
    UUID uid=UUID.randomUUID();
    String shortId=to62System(uid.getMostSignificantBits())+
        to62System(uid.getLeastSignificantBits());

    System.out.println(shortId);
}

static char[] DIGITS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
static int RADIX = DIGITS.length;

public static String to62System(long value) {
    if (value == 0) {
        return "0";
    } else {
        char[] buf = new char[11];
        int charPos = 10;
        long i = value;
        while (i != 0) {
            buf[charPos--] = DIGITS[Math.abs((int) (i % RADIX))];
            i /= RADIX;
        }
        return new String(buf, charPos + 1, (10 - charPos));
    }
}

Am I doing it right or did I overlooked something important?

我做得对还是我忽略了一些重要的事情?

采纳答案by stikkos

I use org.apache.commons.codec.binary.Base64 to convert a UUID into a url-safe unique string that is 22 characters in length and has the same uniqueness as UUID.

我使用 org.apache.commons.codec.binary.Base64 将 UUID 转换为长度为 22 个字符且与 UUID 具有相同唯一性的 url-safe 唯一字符串。

I posted my code on Storing UUID as base64 String

我在将 UUID 存储为 base64 字符串上发布了我的代码

回答by MariuszS

Take a look at FriendlyIdlibrary. This library allow to encode UUIDto Base62string (Url62) and back. Uniqueness is achieved and encoded string is shorter.

看看FriendlyId库。该库允许将UUID编码为Base62字符串(Url62)并返回。实现了唯一性并且编码的字符串更短。

https://github.com/Devskiller/friendly-id

https://github.com/Devskiller/friendly-id

回答by Luke Visinoni

I believe even once you get it down to 22 characters by changing to base whatever, you can safely truncate a few characters and still be reasonably certain you won't get any collisions, as you probably know the astronomically large numbers involved. LOL loved the first guy's response thinking u were just like grabbing some characters from a standard UUID and calling it a day haha

我相信,即使您通过更改为基础将其减少到 22 个字符,您也可以安全地截断几个字符,并且仍然可以合理地确定不会发生任何冲突,因为您可能知道所涉及的天文数字。LOL 喜欢第一个人的回应,认为你就像从标准 UUID 中抓取一些字符并称之为一天哈哈