仅生成8个字符的UUID

UUID库生成32个字符的UUID。

我想生成只有8个字符的UUID,可以吗?

这是不可能的,因为每个定义的UUID是一个16字节的数字。 但是,当然,您可以生成8个字符长的唯一string(请参阅其他答案)。

还要小心生成较长的UUID并对其进行子串处理,因为ID的某些部分可能包含固定字节(例如MAC,DCE和MD5 UUID就是这种情况)。

第一:即使由java UUID.randomUUID或.net GUID生成的唯一ID也不是100%唯一的。 特别是UUID.randomUUID是“唯一”的一个128位(安全)随机值。 所以如果你把它减less到64位,32位,16位(甚至1位),那么它就变得不那么唯一了。

所以这至less是一个基于风险的决定,你的uuid必须持续多久。

第二:我认为当你谈论“只有8个字符”时,你的意思是一串8个正常的可打印字符。

如果你想要一个长度为8个可打印字符的唯一string,你可以使用base64编码。 这意味着每个字符6bit,所以你总共得到48bit(可能不是很独特 – 但也许这对你的应用程序是可以的)

所以方法很简单:创build一个6字节的随机数组

SecureRandom rand; // ... byte[] randomBytes = new byte[16]; rand.nextBytes(randomBytes); 

然后将其转换为Base64string,例如org.apache.commons.codec.binary.Base64

顺便说一句:这取决于你的应用程序是否有更好的方法来创build“uuid”,然后随机。 (如果每秒只创build一次UUID,那么添加一个时间戳是一个好主意)(顺便说一句:如果将两个随机值合并(xor),结果总是至less与最两者的随机)。

你可以尝试从apache.commons的 RandomStringUtils 类 :

 import org.apache.commons.lang3.RandomStringUtils; final int SHORT_ID_LENGTH = 8; // all possible unicode characters String shortId = RandomStringUtils.random(SHORT_UID_LENGTH); 

请记住,它将包含所有可能的字符,既不是URL也不是人性化的。

所以也检查其他方法:

 // HEX: 0-9, af. For example: 6587fddb, c0f182c1 shortId = RandomStringUtils.random(8, "0123456789abcdef"); // az, AZ. For example: eRkgbzeF, MFcWSksx shortId = RandomStringUtils.randomAlphabetic(8); // 0-9. For example: 76091014, 03771122 shortId = RandomStringUtils.randomNumeric(8); // az, AZ, 0-9. For example: WRMcpIk7, s57JwCVA shortId = RandomStringUtils.randomAlphanumeric(8); 

正如其他人所说,ID较小的id碰撞的概率可能是显着的。 看看生日问题如何适用于你的情况。 你可以find很好的解释如何计算在这个答案的近似值。

这个怎么样? 实际上,这个代码最多返回13个字符,但比UUID短。

 import java.nio.ByteBuffer; import java.util.UUID; /** * Generate short UUID (13 characters) * * @return short UUID */ public static String shortUUID() { UUID uuid = UUID.randomUUID(); long l = ByteBuffer.wrap(uuid.toString().getBytes()).getLong(); return Long.toString(l, Character.MAX_RADIX); } 

由于@Cephalopod声明这是不可能的,但你可以缩短一个UUID到22个字符

 public static String encodeUUIDBase64(UUID uuid) { ByteBuffer bb = ByteBuffer.wrap(new byte[16]); bb.putLong(uuid.getMostSignificantBits()); bb.putLong(uuid.getLeastSignificantBits()); return StringUtils.trimTrailingCharacter(BaseEncoding.base64Url().encode(bb.array()), '='); } 

其实我想要基于时间戳的更短的唯一标识符,因此尝试了下面的程序。

nanosecond + ( endians.length * endians.length )组合是可以猜测的。

 public class TimStampShorterUUID { private static final Character [] endians = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; private static ThreadLocal<Character> threadLocal = new ThreadLocal<Character>(); private static AtomicLong iterator = new AtomicLong(-1); public static String generateShorterTxnId() { // Keep this as secure random when we want more secure, in distributed systems int firstLetter = ThreadLocalRandom.current().nextInt(0, (endians.length)); //Sometimes your randomness and timestamp will be same value, //when multiple threads are trying at the same nano second //time hence to differentiate it, utilize the threads requesting //for this value, the possible unique thread numbers == endians.length Character secondLetter = threadLocal.get(); if (secondLetter == null) { synchronized (threadLocal) { if (secondLetter == null) { threadLocal.set(endians[(int) (iterator.incrementAndGet() % endians.length)]); } } secondLetter = threadLocal.get(); } return "" + endians[firstLetter] + secondLetter + System.nanoTime(); } public static void main(String[] args) { Map<String, String> uniqueKeysTestMap = new ConcurrentHashMap<>(); Thread t1 = new Thread() { @Override public void run() { while(true) { String time = generateShorterTxnId(); String result = uniqueKeysTestMap.put(time, ""); if(result != null) { System.out.println("failed! - " + time); } } } }; Thread t2 = new Thread() { @Override public void run() { while(true) { String time = generateShorterTxnId(); String result = uniqueKeysTestMap.put(time, ""); if(result != null) { System.out.println("failed! - " + time); } } } }; Thread t3 = new Thread() { @Override public void run() { while(true) { String time = generateShorterTxnId(); String result = uniqueKeysTestMap.put(time, ""); if(result != null) { System.out.println("failed! - " + time); } } } }; Thread t4 = new Thread() { @Override public void run() { while(true) { String time = generateShorterTxnId(); String result = uniqueKeysTestMap.put(time, ""); if(result != null) { System.out.println("failed! - " + time); } } } }; Thread t5 = new Thread() { @Override public void run() { while(true) { String time = generateShorterTxnId(); String result = uniqueKeysTestMap.put(time, ""); if(result != null) { System.out.println("failed! - " + time); } } } }; Thread t6 = new Thread() { @Override public void run() { while(true) { String time = generateShorterTxnId(); String result = uniqueKeysTestMap.put(time, ""); if(result != null) { System.out.println("failed! - " + time); } } } }; Thread t7 = new Thread() { @Override public void run() { while(true) { String time = generateShorterTxnId(); String result = uniqueKeysTestMap.put(time, ""); if(result != null) { System.out.println("failed! - " + time); } } } }; t1.start(); t2.start(); t3.start(); t4.start(); t5.start(); t6.start(); t7.start(); } } 

更新 :这个代码将在单个JVM上工作,但我们应该考虑分布式JVM,因此我想到两个解决scheme之一与DB和另一个没有DB。

与DB

公司名称(短名3个字符)—- Random_Number —-按键特定的redis COUNTER
(3 char)———————————————- – (2 char)—————-(11 char)

没有数据库

IPADDRESS —- THREAD_NUMBER —- INCR_NUMBER —-纪元毫秒
(5个字符)—————–(2char)———————–(2 char )—————–(6个字符)

一旦完成编码就会更新你。

我不认为这是可能的,但你有一个很好的解决方法。

  1. 使用substring()来截断你的UUID的结尾
  2. 使用code new Random(System.currentTimeMillis()).nextInt(99999999); 这将产生长达8个字符的随机ID。
  3. 生成字母数字ID:

     char[] chars = "abcdefghijklmnopqrstuvwxyzABSDEFGHIJKLMNOPQRSTUVWXYZ1234567890".toCharArray(); Random r = new Random(System.currentTimeMillis()); char[] id = new char[8]; for (int i = 0; i < 8; i++) { id[i] = chars[r.nextInt(chars.length)]; } return new String(id);