zoukankan      html  css  js  c++  java
  • 怎样用java生成GUID与UUID

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

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

    Java代码  收藏代码
    1. import java.util.UUID;  
    2. public class Test {  
    3.  public static void main(String[] args) {  
    4.   UUID uuid = UUID.randomUUID();   
    5.   System.out.println (uuid);  
    6. }  
    7. }  

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


    两种方式生成guid 与uuid 

    需要comm log 库 

    Java代码  收藏代码
    1. /** 
    2.  * @author Administrator 
    3.  * 
    4.  * TODO To change the template for this generated type comment go to 
    5.  * Window - Preferences - Java - Code Style - Code Templates 
    6.  */  
    7. import java.net.InetAddress;  
    8. import java.net.UnknownHostException;  
    9. import java.security.MessageDigest;  
    10. import java.security.NoSuchAlgorithmException;  
    11. import java.security.SecureRandom;  
    12. import java.util.Random;  
    13.   
    14. public class RandomGUID extends Object {  
    15.    protected final org.apache.commons.logging.Log logger = org.apache.commons.logging.LogFactory  
    16.       .getLog(getClass());  
    17.   
    18.    public String valueBeforeMD5 = "";  
    19.    public String valueAfterMD5 = "";  
    20.    private static Random myRand;  
    21.    private static SecureRandom mySecureRand;  
    22.   
    23.    private static String s_id;  
    24.    private static final int PAD_BELOW = 0x10;  
    25.    private static final int TWO_BYTES = 0xFF;  
    26.   
    27.    /* 
    28.     * Static block to take care of one time secureRandom seed. 
    29.     * It takes a few seconds to initialize SecureRandom.  You might 
    30.     * want to consider removing this static block or replacing 
    31.     * it with a "time since first loaded" seed to reduce this time. 
    32.     * This block will run only once per JVM instance. 
    33.       */  
    34.   
    35.    static {  
    36.       mySecureRand = new SecureRandom();  
    37.       long secureInitializer = mySecureRand.nextLong();  
    38.       myRand = new Random(secureInitializer);  
    39.       try {  
    40.          s_id = InetAddress.getLocalHost().toString();  
    41.       } catch (UnknownHostException e) {  
    42.          e.printStackTrace();  
    43.       }  
    44.   
    45.    }  
    46.   
    47.   
    48.    /* 
    49.     * Default constructor.  With no specification of security option, 
    50.     * this constructor defaults to lower security, high performance. 
    51.     */  
    52.    public RandomGUID() {  
    53.       getRandomGUID(false);  
    54.    }  
    55.   
    56.    /* 
    57.     * Constructor with security option.  Setting secure true 
    58.     * enables each random number generated to be cryptographically 
    59.     * strong.  Secure false defaults to the standard Random function seeded 
    60.     * with a single cryptographically strong random number. 
    61.     */  
    62.    public RandomGUID(boolean secure) {  
    63.       getRandomGUID(secure);  
    64.    }  
    65.   
    66.    /* 
    67.     * Method to generate the random GUID 
    68.     */  
    69.    private void getRandomGUID(boolean secure) {  
    70.       MessageDigest md5 = null;  
    71.       StringBuffer sbValueBeforeMD5 = new StringBuffer(128);  
    72.   
    73.       try {  
    74.          md5 = MessageDigest.getInstance("MD5");  
    75.       } catch (NoSuchAlgorithmException e) {  
    76.          logger.error("Error: " + e);  
    77.       }  
    78.   
    79.       try {  
    80.          long time = System.currentTimeMillis();  
    81.          long rand = 0;  
    82.   
    83.          if (secure) {  
    84.             rand = mySecureRand.nextLong();  
    85.          } else {  
    86.             rand = myRand.nextLong();  
    87.          }  
    88.          sbValueBeforeMD5.append(s_id);  
    89.          sbValueBeforeMD5.append(":");  
    90.          sbValueBeforeMD5.append(Long.toString(time));  
    91.          sbValueBeforeMD5.append(":");  
    92.          sbValueBeforeMD5.append(Long.toString(rand));  
    93.   
    94.          valueBeforeMD5 = sbValueBeforeMD5.toString();  
    95.          md5.update(valueBeforeMD5.getBytes());  
    96.   
    97.          byte[] array = md5.digest();  
    98.          StringBuffer sb = new StringBuffer(32);  
    99.          for (int j = 0; j < array.length; ++j) {  
    100.             int b = array[j] & TWO_BYTES;  
    101.             if (b < PAD_BELOW)  
    102.                sb.append('0');  
    103.             sb.append(Integer.toHexString(b));  
    104.          }  
    105.   
    106.          valueAfterMD5 = sb.toString();  
    107.   
    108.       } catch (Exception e) {  
    109.          logger.error("Error:" + e);  
    110.       }  
    111.    }  
    112.   
    113.    /* 
    114.     * Convert to the standard format for GUID 
    115.     * (Useful for SQL Server UniqueIdentifiers, etc.) 
    116.     * Example: C2FEEEAC-CFCD-11D1-8B05-00600806D9B6 
    117.     */  
    118.    public String toString() {  
    119.       String raw = valueAfterMD5.toUpperCase();  
    120.       StringBuffer sb = new StringBuffer(64);  
    121.       sb.append(raw.substring(08));  
    122.       sb.append("-");  
    123.       sb.append(raw.substring(812));  
    124.       sb.append("-");  
    125.       sb.append(raw.substring(1216));  
    126.       sb.append("-");  
    127.       sb.append(raw.substring(1620));  
    128.       sb.append("-");  
    129.       sb.append(raw.substring(20));  
    130.   
    131.       return sb.toString();  
    132.    }  
    133.   
    134.   
    135.      // Demonstraton and self test of class  
    136.      public static void main(String args[]) {  
    137.        for (int i=0; i< 100; i++) {  
    138.          RandomGUID myGUID = new RandomGUID();  
    139.          System.out.println("Seeding String=" + myGUID.valueBeforeMD5);  
    140.          System.out.println("rawGUID=" + myGUID.valueAfterMD5);  
    141.          System.out.println("RandomGUID=" + myGUID.toString());  
    142.        }  
    143.      }  
    144.   
    145.   
    146. }  



    同样 

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



    UUID是指在一台机器上生成的数字,它保证对在同一时空中的所有机器都是唯一的。通常平台会提供生成UUID的API。UUID按照开放软件基金会(OSF)制定的标准计算,用到了以太网卡地址、纳秒级时间、芯片ID码和许多可能的数字。由以下几部分的组合:当前日期和时间(UUID的第一个部分与时间有关,如果你在生成一个UUID之后,过几秒又生成一个UUID,则第一个部分不同,其余相同),时钟序列,全局唯一的IEEE机器识别号(如果有网卡,从网卡获得,没有网卡以其他方式获得),UUID的唯一缺陷在于生成的结果串会比较长。关于UUID这个标准使用最普遍的是微软的GUID(Globals Unique Identifiers)。 

  • 相关阅读:
    MVC设计模式
    二十三种设计模式
    描绘质量属性的六个常见属性场景。
    《架构漫谈》读后感
    软件架构师的工作过程
    《架构之美》阅读笔记06
    《架构之美》阅读笔记05
    《架构之法》阅读笔记04
    《架构之美》阅读笔记03
    《构架之美》阅读笔记02
  • 原文地址:https://www.cnblogs.com/zhuzhengwen1983/p/3633084.html
Copyright © 2011-2022 走看看