UUID生成

 

      关于UUID的标准参考->http://en.wikipedia.org/wiki/Universally_unique_identifier,JAVA1.7 JDK支持其中version3(基于名称)和version4(随机)的UUID生成方式。

Version3

      Version 3 UUIDs use a scheme deriving a UUID via MD5 from a URL, a fully qualified domain name, an object identifier, a distinguished name (DN as used in Lightweight Directory Access Protocol), or on names in unspecified namespaces. Version 3 UUIDs have the form xxxxxxxx-xxxx-3xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal digit and y is one of 8, 9, A, or B.

Version4

       Version 4 UUIDs use a scheme relying only on random numbers. This algorithm sets the version number (4 bits) as well as two reserved bits. All other bits (the remaining 122 bits) are set using a random or pseudorandom data source. Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal digit and y is one of 8, 9, A, or B (e.g., f47ac10b-58cc-4372-a567-0e02b2c3d479).

       Version4是基于随机数字生成的UUID,因为没有那么大的数据量无法测试生成UUID是否是绝对唯一的,因此考虑使用Version3生成UUID。以下代码也适用于不同机器集群中生成UUID。为了减少UUID生成的时间,可以一次生成多个UUID,并存放到一个UUID缓存中。

package com.company.projects.gis.md5;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.UUID;
/**
 * 采用MD5加密解密
 * @author tfq
 * @datetime 2011-10-13
 */
public class UUIDUtil {
	public static long seed = 0 ;
	
	private static String mac = "" ; 
	
	static{
		//获取mac地址
		try {
			NetworkInterface networkInterface = NetworkInterface.getByInetAddress(InetAddress.getLocalHost());
			byte[] macByte = networkInterface.getHardwareAddress() ;
			StringBuffer sb = new StringBuffer("");
			for(int i=0; i<macByte.length; i++) {
				if(i!=0) {
					sb.append("-");
				}
				//字节转换为整数
				String str = Integer.toHexString(macByte[i]&0xff);
				if(str.length()==1) {
					sb.append("0"+str);
				}else {
					sb.append(str);
				}
			}
			//设置mac地址
			mac = sb.toString() ;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 根据mac地址、时间和seed生成UUID,生成UUID是经过MD5加密过的,能够避免生成id连续的UUID
	 * @return
	 */
	public synchronized static String getUUID(){
		if(seed > Long.MAX_VALUE){
			seed = Long.MIN_VALUE  ;
		}
		++seed ;
		UUID uuid = UUID.nameUUIDFromBytes((mac+(System.currentTimeMillis())+seed).getBytes()) ;
		return uuid.toString() ;
	}
	// 测试主函数
	public static void main(String args[]) throws UnknownHostException, SocketException {
		for (int i = 0; i < 10; i++) {
			System.out.println(getUUID());
		}
	}
}

hibernate生成uuid

      hibernate提供了多种生成唯一主键标识的方式,其中包括uuid,uuid是由IP+JVM启动时间+当前时间+计数标识来生成的。可以在多机分布式集群和单机集群中生成uuid,Hibernate中生成uuid的类为org.hibernate.id.UUIDHexGenerator。

 

你可能感兴趣的:(uuid)