文章來源:http://www.cnblogs.com/jdonson/archive/2009/07/22/1528466.html
GUID是一個128位長的數字,一般用16進制表示。算法的核心思想是結合機器的網卡、當地時間、一個隨即數來生成GUID。從理論上講,如果一臺機器每秒產生10000000個GUID,則可以保證(概率意義上)3240年不重復。
UUID是1.5中新增的一個類,在java.util下,用它可以產生一個號稱全球唯一的ID
package com.mytest;import java.util.UUID;public class UTest { public static void main(String[] args) { UUID uuid = UUID.randomUUID(); System.out.PRintln(uuid); }}UUID(Universally Unique Identifier)全局唯一標識符,是指在一臺機器上生成的數字,它保證對在同一時空中的所有機器都是唯一的。按照開放軟件基金會(OSF)制定的標準計算,用到了以太網卡地址、納秒級時間、芯片ID碼和許多可能的數字。由以下幾部分的組合:當前日期和時間(UUID的第一個部分與時間有關,如果你在生成一個UUID之后,過幾秒又生成一個UUID,則第一個部分不同,其余相同),時鐘序列,全局唯一的IEEE機器識別號(如果有網卡,從網卡獲得,沒有網卡以其他方式獲得),UUID的唯一缺陷在于生成的結果串會比較長。
在Java中生成UUID主要有以下幾種方式:
JDK1.5如果使用的JDK1.5的話,那么生成UUID變成了一件簡單的事,因為JDK實現了UUID: java.util.UUID,直接調用即UUID uuid = UUID.randomUUID(); String s = UUID.randomUUID().toString();//用來生成數據庫的主鍵id非常不錯。。 UID是由一個十六位的數字組成,表現出來的形式例如:**
550E8400-E29B-11D4-A716-446655440000//下面就是實現為數據庫獲取一個唯一的主鍵id的代碼
public class UUIDGenerator { public UUIDGenerator() { } /** * 獲得一個UUID * @return String UUID */ public static String getUUID(){ String s = UUID.randomUUID().toString(); //去掉“-”符號 return s.substring(0,8)+s.substring(9,13)+s.substring(14,18)+s.substring(19,23)+s.substring(24); } /** * 獲得指定數目的UUID * @param number int 需要獲得的UUID數量 * @return String[] 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]); } } } 兩種方式生成guid 與uuid需要comm log 庫
/** * @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()); } }}同樣
UUID uuid = UUID.randomUUID();System.out.println("{"+uuid.toString()+"}");關于UUID這個標準使用最普遍的是微軟的GUID(Globals Unique Identifiers)。
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 等等。
以下是具體生成UUID的例子:
view plaincopy to clipboardprint?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]); } } } 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]); } }}結果:
view plaincopy to clipboardprint?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,4cdbc040657a4847b2667e31d9e2c3d9ss[1]=====72297c88-4260-4c05-9b05-d28bfb11d10b,72297c8842604c059b05d28bfb11d10bss[2]=====6d513b6a-69bd-4f79-b94c-d65fc841ea95,6d513b6a69bd4f79b94cd65fc841ea95ss[3]=====d897a7d3-87a3-4e38-9e0b-71013a6dbe4c,d897a7d387a34e389e0b71013a6dbe4css[4]=====5709f0ba-31e3-42bd-a28d-03485b257c94,5709f0ba31e342bda28d03485b257c94ss[5]=====530fbb8c-eec9-48d1-ae1b-5f792daf09f3,530fbb8ceec948d1ae1b5f792daf09f3ss[6]=====4bf07297-65b2-45ca-b905-6fc6f2f39158,4bf0729765b245cab9056fc6f2f39158ss[7]=====6e5a0e85-b4a0-485f-be54-a758115317e1,6e5a0e85b4a0485fbe54a758115317e1ss[8]=====245accec-3c12-4642-967f-e476cef558c4,245accec3c124642967fe476cef558c4ss[9]=====ddd4b5a9-fecd-446c-bd78-63b70bb500a1,ddd4b5a9fecd446cbd7863b70bb500a1可以看出,UUID 是指在一臺機器上生成的數字,它保證對在同一時空中的所有機器都是唯一的。通常平臺會提供生成的API。按照開放軟件基金會(OSF)制定的標準計算,用到了以太網卡地址、納秒級時間、芯片ID碼和許多可能的數字
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)的組件。
新聞熱點
疑難解答