怎样用java生成GUID与UUID

 GUID是一个128位长的数字,一般用16进制表示。算法的核心思想是结合机器的网卡、当地时间、一个随机数来生成GUID。从理论上讲,如果一台机器每秒产生10000000个GUID,则可以保证(概率意义上)3240年不重复。 

 UUID是1.5中新增的一个类,在java.util下,用它可以产生一个号称全球唯一的ID 

Java代码  
import java.util.UUID;  
public class Test {  
 public static void main(String[] args) {  
  UUID uuid = UUID.randomUUID();   
  System.out.println (uuid);  
}  
}

编译运行输出: 
07ca3dec-b674-41d0-af9e-9c37583b08bb 

两种方式生成guid 与uuid 

需要comm log 库

Java代码    
/** 
 * @author Administrator 
 * 
 * TODO To change the template for this generated type comment go to 
 * Window - Preferences - Java - Code Style - Code Templates 
 */  
import java.net.InetAddress;  
import java.net.UnknownHostException;  
import java.security.MessageDigest;  
import java.security.NoSuchAlgorithmException;  
import java.security.SecureRandom;  
import java.util.Random;  
  
public class RandomGUID extends Object {  
   protected final org.apache.commons.logging.Log logger = org.apache.commons.logging.LogFactory  
      .getLog(getClass());  
  
   public String valueBeforeMD5 = "";  
   public String valueAfterMD5 = "";  
   private static Random myRand;  
   private static SecureRandom mySecureRand;  
  
   private static String s_id;  
   private static final int PAD_BELOW = 0x10;  
   private static final int TWO_BYTES = 0xFF;  
  
   /* 
    * Static block to take care of one time secureRandom seed. 
    * It takes a few seconds to initialize SecureRandom.  You might 
    * want to consider removing this static block or replacing 
    * it with a "time since first loaded" seed to reduce this time. 
    * This block will run only once per JVM instance. 
      */  
  
   static {  
      mySecureRand = new SecureRandom();  
      long secureInitializer = mySecureRand.nextLong();  
      myRand = new Random(secureInitializer);  
      try {  
         s_id = InetAddress.getLocalHost().toString();  
      } catch (UnknownHostException e) {  
         e.printStackTrace();  
      }  
  
   }  
  
  
   /* 
    * Default constructor.  With no specification of security option, 
    * this constructor defaults to lower security, high performance. 
    */  
   public RandomGUID() {  
      getRandomGUID(false);  
   }  
  
   /* 
    * Constructor with security option.  Setting secure true 
    * enables each random number generated to be cryptographically 
    * strong.  Secure false defaults to the standard Random function seeded 
    * with a single cryptographically strong random number. 
    */  
   public RandomGUID(boolean secure) {  
      getRandomGUID(secure);  
   }  
  
   /* 
    * Method to generate the random GUID 
    */  
   private void getRandomGUID(boolean secure) {  
      MessageDigest md5 = null;  
      StringBuffer sbValueBeforeMD5 = new StringBuffer(128);  
  
      try {  
         md5 = MessageDigest.getInstance("MD5");  
      } catch (NoSuchAlgorithmException e) {  
         logger.error("Error: " + e);  
      }  
  
      try {  
         long time = System.currentTimeMillis();  
         long rand = 0;  
  
         if (secure) {  
            rand = mySecureRand.nextLong();  
         } else {  
            rand = myRand.nextLong();  
         }  
         sbValueBeforeMD5.append(s_id);  
         sbValueBeforeMD5.append(":");  
         sbValueBeforeMD5.append(Long.toString(time));  
         sbValueBeforeMD5.append(":");  
         sbValueBeforeMD5.append(Long.toString(rand));  
  
         valueBeforeMD5 = sbValueBeforeMD5.toString();  
         md5.update(valueBeforeMD5.getBytes());  
  
         byte[] array = md5.digest();  
         StringBuffer sb = new StringBuffer(32);  
         for (int j = 0; j < array.length; ++j) {  
            int b = array[j] & TWO_BYTES;  
            if (b < PAD_BELOW)  
               sb.append('0');  
            sb.append(Integer.toHexString(b));  
         }  
  
         valueAfterMD5 = sb.toString();  
  
      } catch (Exception e) {  
         logger.error("Error:" + e);  
      }  
   }  
  
   /* 
    * Convert to the standard format for GUID 
    * (Useful for SQL Server UniqueIdentifiers, etc.) 
    * Example: C2FEEEAC-CFCD-11D1-8B05-00600806D9B6 
    */  
   public String toString() {  
      String raw = valueAfterMD5.toUpperCase();  
      StringBuffer sb = new StringBuffer(64);  
      sb.append(raw.substring(0, 8));  
      sb.append("-");  
      sb.append(raw.substring(8, 12));  
      sb.append("-");  
      sb.append(raw.substring(12, 16));  
      sb.append("-");  
      sb.append(raw.substring(16, 20));  
      sb.append("-");  
      sb.append(raw.substring(20));  
  
      return sb.toString();  
   }  
  
  
     // Demonstraton and self test of class  
     public static void main(String args[]) {  
       for (int i=0; i< 100; i++) {  
         RandomGUID myGUID = new RandomGUID();  
         System.out.println("Seeding String=" + myGUID.valueBeforeMD5);  
         System.out.println("rawGUID=" + myGUID.valueAfterMD5);  
         System.out.println("RandomGUID=" + myGUID.toString());  
       }  
     }  
  
  
}

同样 

Java代码  
UUID uuid = UUID.randomUUID();  
System.out.println("{"+uuid.toString()+"}"); 

UUID含义是通用唯一识别码 (Universally Unique Identifier),这 是一个软件建构的标准,也是被开源软件基金会 (Open Software Foundation, OSF) 的组织在分布式计算环境 (Distributed Computing Environment, DCE) 领域的一部份。UUID 的目的,是让分布式系统中的所有元素,都能有唯一的辨识资讯,而不需要透过中央控制端来做辨识资讯的指定。如此一来,每个人都可以建立不与其它人冲突的 UUID。在这样的情况下,就不需考虑数据库建立时的名称重复问题。目前最广泛应用的 UUID,即是微软的 Microsoft's Globally Unique Identifiers (GUIDs),而其他重要的应用,则有 Linux ext2/ext3 档案系统、LUKS 加密分割区、GNOME、KDE、Mac OS X 等等。

package test;

import java.util.UUID;

public class UUIDGenerator {
 public UUIDGenerator() {
 }

 public static String getUUID() {
  UUID uuid = UUID.randomUUID();
  String str = uuid.toString();
  // 去掉"-"符号
  String temp = str.substring(0, 8) + str.substring(9, 13) + str.substring(14, 18) + str.substring(19, 23) + str.substring(24);
  return str+","+temp;
 }
 //获得指定数量的UUID
 public static String[] getUUID(int number) {
  if (number < 1) {
   return null;
  }
  String[] ss = new String[number];
  for (int i = 0; i < number; i++) {
   ss[i] = getUUID();
  }
  return ss;
 }

 public static void main(String[] args) {
  String[] ss = getUUID(10);
  for (int i = 0; i < ss.length; i++) {
   System.out.println("ss["+i+"]====="+ss[i]);
  }
 }
}

结果:

ss[0]=====4cdbc040-657a-4847-b266-7e31d9e2c3d9,4cdbc040657a4847b2667e31d9e2c3d9   
ss[1]=====72297c88-4260-4c05-9b05-d28bfb11d10b,72297c8842604c059b05d28bfb11d10b   
ss[2]=====6d513b6a-69bd-4f79-b94c-d65fc841ea95,6d513b6a69bd4f79b94cd65fc841ea95   
ss[3]=====d897a7d3-87a3-4e38-9e0b-71013a6dbe4c,d897a7d387a34e389e0b71013a6dbe4c   
ss[4]=====5709f0ba-31e3-42bd-a28d-03485b257c94,5709f0ba31e342bda28d03485b257c94   
ss[5]=====530fbb8c-eec9-48d1-ae1b-5f792daf09f3,530fbb8ceec948d1ae1b5f792daf09f3   
ss[6]=====4bf07297-65b2-45ca-b905-6fc6f2f39158,4bf0729765b245cab9056fc6f2f39158   
ss[7]=====6e5a0e85-b4a0-485f-be54-a758115317e1,6e5a0e85b4a0485fbe54a758115317e1   
ss[8]=====245accec-3c12-4642-967f-e476cef558c4,245accec3c124642967fe476cef558c4   
ss[9]=====ddd4b5a9-fecd-446c-bd78-63b70bb500a1,ddd4b5a9fecd446cbd7863b70bb500a1  
ss[0]=====4cdbc040-657a-4847-b266-7e31d9e2c3d9,4cdbc040657a4847b2667e31d9e2c3d9
ss[1]=====72297c88-4260-4c05-9b05-d28bfb11d10b,72297c8842604c059b05d28bfb11d10b
ss[2]=====6d513b6a-69bd-4f79-b94c-d65fc841ea95,6d513b6a69bd4f79b94cd65fc841ea95
ss[3]=====d897a7d3-87a3-4e38-9e0b-71013a6dbe4c,d897a7d387a34e389e0b71013a6dbe4c
ss[4]=====5709f0ba-31e3-42bd-a28d-03485b257c94,5709f0ba31e342bda28d03485b257c94
ss[5]=====530fbb8c-eec9-48d1-ae1b-5f792daf09f3,530fbb8ceec948d1ae1b5f792daf09f3
ss[6]=====4bf07297-65b2-45ca-b905-6fc6f2f39158,4bf0729765b245cab9056fc6f2f39158
ss[7]=====6e5a0e85-b4a0-485f-be54-a758115317e1,6e5a0e85b4a0485fbe54a758115317e1
ss[8]=====245accec-3c12-4642-967f-e476cef558c4,245accec3c124642967fe476cef558c4
ss[9]=====ddd4b5a9-fecd-446c-bd78-63b70bb500a1,ddd4b5a9fecd446cbd7863b70bb500a1

UUID由以下几部分的组合:

  (1)当前日期和时间,UUID的第一个部分与时间有关,如果你在生成一个UUID之后,过几秒又生成一个UUID,则第一个部分不同,其余相同。

  (2)时钟序列

  (3)全局唯一的IEEE机器识别号,如果有网卡,从网卡MAC地址获得,没有网卡以其他方式获得。

  UUID的唯一缺陷在于生成的结果串会比较长。关于UUID这个标准使用最普遍的是微软的GUID(Globals Unique Identifiers)。在ColdFusion中可以用CreateUUID()函数很简单的生成UUID,其格式为:xxxxxxxx-xxxx- xxxx-xxxxxxxxxxxxxxxx(8-4-4-16),其中每个 x 是 0-9 或 a-f 范围内的一个十六进制的数字。而标准的UUID格式为:xxxxxxxx-xxxx-xxxx-xxxxxx-xxxxxxxxxx (8-4-4-4-12),可以从cflib 下载CreateGUID() UDF进行转换。

  使用UUID的好处在分布式的软件系统中(比如:DCE/RPC, COM+,CORBA)就能体现出来,它能保证每个节点所生成的标识都不会重复,并且随着WEB服务等整合技术的发展,UUID的优势将更加明显。根据使用的特定机制,UUID不仅需要保证是彼此不相同的,或者最少也是与公元3400年之前其他任何生成的通用惟一标识符有非常大的区别。

  通用惟一标识符还可以用来指向大多数的可能的物体。微软和其他一些软件公司都倾向使用全球惟一标识符(GUID),这也是通用惟一标识符的一种类型,可用来指向组建对象模块对象和其他的软件组件。第一个通用惟一标识符是在网罗计算机系统(NCS)中创建,并且随后成为开放软件基金会(OSF)的分布式计算环境(DCE)的组件。

posted on 2013-07-04 12:59  duanxz  阅读(47018)  评论(0编辑  收藏  举报