欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

UUID在Java中的两种产生方式

程序员文章站 2022-07-12 17:02:30
...

需求:

集群环境下需要产生uuid,uuid的作用不言而喻

转发请注明出处:http://snv.iteye.com/

环境:

<dependency>
	<groupId>org.safehaus.jug</groupId>
	<artifactId>jug</artifactId>
	<version>2.0.0</version>
	 <classifier>asl</classifier>
</dependency>  

或:

<dependency>
	<groupId>org.safehaus.jug</groupId>
	<artifactId>jug</artifactId>
	<version>2.0.0</version>
	<classifier>lgpl</classifier>
</dependency>

两个的区分只是license不一样

基于JUG实现:

UUIDGenerator generator=UUIDGenerator.getInstance();
UUID uuid=generator.generateRandomBasedUUID();
System.out.println(uuid.toString());
uuid=generator.generateTimeBasedUUID();
System.out.println(uuid.toString());

基于JDK的实现:

String uuidStr=java.util.UUID.randomUUID().toString();
System.out.println(uuidStr);

PS:

两种方式我单机测试jdk的性能高不知道各位看官有什么看法,测试如下:

public static void cost() throws Exception {
	UUIDGenerator generator=UUIDGenerator.getInstance();
	final int size=10000000;
	long now=System.currentTimeMillis();
	for (int i = 0; i < size; i++) {
		UUID uuid=generator.generateRandomBasedUUID();
		String uidStr=(uuid.toString());
	}
	long time1=System.currentTimeMillis();
	for (int i = 0; i < size; i++) {
		String uidStr=java.util.UUID.randomUUID().toString();
	}
	long end=System.currentTimeMillis();
	System.out.println("jug cost:"+(time1-now));
	System.out.println("jdk cost:"+(end-time1));
}

结果:

jug cost:11209
jdk cost:10114