如何在Java中创build唯一的ID?

我正在寻找最好的方式来创build一个独特的ID作为一个string在Java中。

任何指导赞赏,谢谢。

我应该提到我正在使用Java 5。

创build一个UUID 。

String uniqueID = UUID.randomUUID().toString(); 

如果您想要简短的人类可读的ID,并且只需要它们在每个JVM运行时都是唯一的:

 private static long idCounter = 0; public static synchronized String createID() { return String.valueOf(idCounter++); } 

编辑:替代build议在评论 – 这依赖于引擎盖下的“魔术”的线程安全,但更具扩展性,同样安全:

 private static AtomicLong idCounter = new AtomicLong(); public static String createID() { return String.valueOf(idCounter.getAndIncrement()); } 

java.util.UUID :toString()方法

这里是我的两个IdFactory :我以前实现了一个IdFactory类,它以[主机名] – [应用程序开始时间] – [当前时间] – [鉴别器]的格式创buildID。 这在很大程度上保证了ID在JVM实例中是唯一的,同时保持了ID的可读性(虽然很长)。 以下是代码,以防万一:

 public class IdFactoryImpl implements IdFactory { private final String hostName; private final long creationTimeMillis; private long lastTimeMillis; private long discriminator; public IdFactoryImpl() throws UnknownHostException { this.hostName = InetAddress.getLocalHost().getHostAddress(); this.creationTimeMillis = System.currentTimeMillis(); this.lastTimeMillis = creationTimeMillis; } public synchronized Serializable createId() { String id; long now = System.currentTimeMillis(); if (now == lastTimeMillis) { ++discriminator; } else { discriminator = 0; } // creationTimeMillis used to prevent multiple instances of the JVM // running on the same host returning clashing IDs. // The only way a clash could occur is if the applications started at // exactly the same time. id = String.format("%s-%d-%d-%d", hostName, creationTimeMillis, now, discriminator); lastTimeMillis = now; return id; } public static void main(String[] args) throws UnknownHostException { IdFactory fact = new IdFactoryImpl(); for (int i=0; i<1000; ++i) { System.err.println(fact.createId()); } } } 

Java – 生成唯一的ID

UUID是在Java中生成唯一ID的最快最容易的方法。

 import java.util.UUID; public class UniqueIDTest { public static void main(String[] args) { UUID uniqueKey = UUID.randomUUID(); System.out.println (uniqueKey); } } 

这为UUID生成增加了更多的随机性,但是确保每个生成的ID是相同的长度

 import org.apache.commons.codec.digest.DigestUtils; import java.util.UUID; public String createSalt() { String ts = String.valueOf(System.currentTimeMillis()); String rand = UUID.randomUUID().toString(); return DigestUtils.sha1Hex(ts + rand); } 

恕我直言aperkins提供了一个优雅的解决scheme原因是本地和使用较less的代码。 但是,如果您需要较短的ID,则可以使用此方法来减less生成的string长度:

 // usage: GenerateShortUUID.next(); import java.util.UUID; public class GenerateShortUUID() { private GenerateShortUUID() { } // singleton public static String next() { UUID u = UUID.randomUUID(); return toIDString(u.getMostSignificantBits()) + toIDString(u.getLeastSignificantBits()); } private static String toIDString(long i) { char[] buf = new char[32]; int z = 64; // 1 << 6; int cp = 32; long b = z - 1; do { buf[--cp] = DIGITS66[(int)(i & b)]; i >>>= 6; } while (i != 0); return new String(buf, cp, (32-cp)); } // array de 64+2 digitos private final static char[] DIGITS66 = { '0','1','2','3','4','5','6','7','8','9', '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', '-','.','_','~' }; } 

我们可以使用UUID在java中创build一个唯一的ID,并在UUID上调用randomUUID()方法。

String uniqueID = UUID.randomUUID()。toString();

这将生成返回types为String的随机uniqueID。

有三种方法可以在java中生成唯一的id。

1)UUID类提供了一个简单的方法来生成唯一的ID。

  UUID id = UUID.randomUUID(); System.out.println(id); 

2)SecureRandom和MessageDigest

 //initialization of the application SecureRandom prng = SecureRandom.getInstance("SHA1PRNG"); //generate a random number String randomNum = new Integer(prng.nextInt()).toString(); //get its digest MessageDigest sha = MessageDigest.getInstance("SHA-1"); byte[] result = sha.digest(randomNum.getBytes()); System.out.println("Random number: " + randomNum); System.out.println("Message digest: " + new String(result)); 

3)使用java.rmi.server.UID

 UID userId = new UID(); System.out.println("userId: " + userId); 
 enter code here 

用于生成唯一ID的程序

 class Test { public static void main(String arg[]) { String s = ""; double d; for (int i = 1; i <= 16; i++) { d = Math.random() * 10; s = s + ((int)d); if (i % 4 == 0 && i != 16) { s = s + "-"; } } System.out.println(s); } } 

输出:

 7954-7605-1827-4795 1991-4912-4912-3008