java生成UUID


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的例子:

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]);
        }
    }
}

 

結果:

[java]  view plaincopy
  1. ss[0]=====4cdbc040-657a-4847-b266-7e31d9e2c3d9,4cdbc040657a4847b2667e31d9e2c3d9  
  2. ss[1]=====72297c88-4260-4c05-9b05-d28bfb11d10b,72297c8842604c059b05d28bfb11d10b  
  3. ss[2]=====6d513b6a-69bd-4f79-b94c-d65fc841ea95,6d513b6a69bd4f79b94cd65fc841ea95  
  4. ss[3]=====d897a7d3-87a3-4e38-9e0b-71013a6dbe4c,d897a7d387a34e389e0b71013a6dbe4c  
  5. ss[4]=====5709f0ba-31e3-42bd-a28d-03485b257c94,5709f0ba31e342bda28d03485b257c94  
  6. ss[5]=====530fbb8c-eec9-48d1-ae1b-5f792daf09f3,530fbb8ceec948d1ae1b5f792daf09f3  
  7. ss[6]=====4bf07297-65b2-45ca-b905-6fc6f2f39158,4bf0729765b245cab9056fc6f2f39158  
  8. ss[7]=====6e5a0e85-b4a0-485f-be54-a758115317e1,6e5a0e85b4a0485fbe54a758115317e1  
  9. ss[8]=====245accec-3c12-4642-967f-e476cef558c4,245accec3c124642967fe476cef558c4  
  10. ss[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)的組件。

 

package com.cib.cap4j.cfn.util;

import java.net.InetAddress;
import java.security.SecureRandom;

/**
 * UUID工具類,用來產生一個唯一的標記號UUID
 */
public class UUIDGenerator {
    private static SecureRandom SEEDER_STATIC = null;
    private static byte[] ADDRESS             = null;
    private static String MID_VALUE_STATIC    = null;
    private String midValue = null;
    private SecureRandom seeder = null;

    static {
        try {
            ADDRESS = InetAddress.getLocalHost().getAddress();
            StringBuffer buffer = new StringBuffer(8);
            buffer.append(toHex(toInt(ADDRESS), 8));
            MID_VALUE_STATIC = buffer.toString();
            SEEDER_STATIC = new SecureRandom();
            SEEDER_STATIC.nextInt();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public UUIDGenerator() {
        StringBuffer buffer = new StringBuffer(16);
        buffer.append(MID_VALUE_STATIC);
        buffer.append(toHex(System.identityHashCode(this), 8));
        midValue = buffer.toString();
        seeder = new SecureRandom();
        seeder.nextInt();
    }

    /**
     * 該方法用來產生一個32位的唯一的標記String
     * 
     * @param obj
     *            傳入一個參考的對象
     * @return
     */
    public static String generate(Object obj) {
        StringBuffer uid = new StringBuffer(32);

        // get the system time
        long currentTimeMillis = System.currentTimeMillis();
        uid.append(toHex((int) (currentTimeMillis & -1L), 8));

        // get the internet address
        uid.append(MID_VALUE_STATIC);

        // get the object hash value
        uid.append(toHex(System.identityHashCode(obj), 8));

        // get the random number
        uid.append(toHex(getRandom(), 8));

        return uid.toString();
    }

    /**
     * 該方法用來產生一個32位的String唯一標記
     */
    public String generate() {
        StringBuffer uid = new StringBuffer(32);

        // get the system time
        long currentTimeMillis = System.currentTimeMillis();
        uid.append(toHex((int) (currentTimeMillis & -1L), 8));

        // get the internet address
        uid.append(midValue);

        // get the random number
        uid.append(toHex(seeder.nextInt(), 8));

        return uid.toString();
    }

    private static String toHex(int value, int length) {
        char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        StringBuffer buffer = new StringBuffer(length);
        int shift = length - 1 << 2;
        for (int i = -1; ++i < length;) {
            buffer.append(hexDigits[value >> shift & 0xf]);
            value <<= 4;
        }

        return buffer.toString();
    }

    private static int toInt(byte[] bytes) {
        int value = 0;
        for (int i = -1; ++i < bytes.length;) {
            value <<= 8;
            value |= bytes[i];
        }

        return value;
    }

    private static synchronized int getRandom() {
        return SEEDER_STATIC.nextInt();
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM