如何在 Java 中创建唯一 ID?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1389736/
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
How do I create a unique ID in Java?
提问by Supertux
I'm looking for the best way to create a unique ID as a String in Java.
我正在寻找在 Java 中创建唯一 ID 作为字符串的最佳方法。
Any guidance appreciated, thanks.
任何指导表示赞赏,谢谢。
I should mention I'm using Java 5.
我应该提到我正在使用 Java 5。
回答by Mitch Wheat
java.util.UUID
: toString() method
java.util.UUID
: toString() 方法
回答by Michael Borgwardt
If you want short, human-readable IDs and only need them to be unique per JVM run:
如果您想要简短的、人类可读的 ID,并且只需要它们在每次 JVM 运行时都是唯一的:
private static long idCounter = 0;
public static synchronized String createID()
{
return String.valueOf(idCounter++);
}
Edit:Alternative suggested in the comments - this relies on under-the-hood "magic" for thread safety, but is more scalable and just as safe:
编辑:评论中建议的替代方案 - 这依赖于线程安全的幕后“魔法”,但更具可扩展性且同样安全:
private static AtomicLong idCounter = new AtomicLong();
public static String createID()
{
return String.valueOf(idCounter.getAndIncrement());
}
回答by Adamski
Here's my two cent's worth: I've previously implemented an IdFactory
class that created IDs in the format [host name]-[application start time]-[current time]-[discriminator]. This largely guaranteed that IDs were unique across JVM instances whilst keeping the IDs readable (albeit quite long). Here's the code in case it's of any use:
这是我的两分钱:我之前实现了一个IdFactory
类,该类以[host name]-[application start time]-[current time]-[discriminator]格式创建 ID 。这在很大程度上保证了 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());
}
}
}
回答by UdayKiran Pulipati
Java – Generate Unique ID
Java - 生成唯一 ID
UUID is the fastest and easiest way to generate unique ID in Java.
UUID 是在 Java 中生成唯一 ID 的最快和最简单的方法。
import java.util.UUID;
public class UniqueIDTest {
public static void main(String[] args) {
UUID uniqueKey = UUID.randomUUID();
System.out.println (uniqueKey);
}
}
回答by rharari
IMHO aperkinsprovided an an elegant solution cause is native and use less code. But if you need a shorter ID you can use this approach to reduce the generated String length:
恕我直言aperkins提供了一个优雅的解决方案,原因是原生的并且使用更少的代码。但是如果你需要一个更短的 ID,你可以使用这种方法来减少生成的 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',
'-','.','_','~'
};
}
回答by Prabhat
We can create a unique ID in java by using the UUID
and call the method like randomUUID()
on UUID
.
我们可以在 java 中创建一个唯一的 ID,使用UUID
并调用类似randomUUID()
on的方法UUID
。
String uniqueID = UUID.randomUUID().toString();
This will generate the random uniqueID
whose return type will be String
.
这将生成uniqueID
返回类型为 的随机数String
。
回答by Robert Alderson
This adds a bit more randomness to the UUID generation but ensures each generated id is the same length
这为 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);
}
回答by Md Ayub Ali Sarker
There are three way to generate unique id in java.
java中生成唯一id的方法有3种。
1) the UUID class provides a simple means for generating unique ids.
1) UUID 类提供了一种生成唯一 ID 的简单方法。
UUID id = UUID.randomUUID();
System.out.println(id);
2) SecureRandom and MessageDigest
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) using a java.rmi.server.UID
3) 使用 java.rmi.server.UID
UID userId = new UID();
System.out.println("userId: " + userId);
回答by simhumileco
Unique ID with count information
带有计数信息的唯一 ID
import java.util.concurrent.atomic.AtomicLong;
public class RandomIdUtils {
private static AtomicLong atomicCounter = new AtomicLong();
public static String createId() {
String currentCounter = String.valueOf(atomicCounter.getAndIncrement());
String uniqueId = UUID.randomUUID().toString();
return uniqueId + "-" + currentCounter;
}
}