Java uuid generation, javauuid generation

Source: Internet
Author: User

Java uuid generation, javauuid generation

UUID refers to the number generated on a machine, which ensures that all machines in the same time and space are unique. Generally, the platform provides APIs for UUID generation. UUID is calculated according to the standards set by the Open Software Foundation (OSF), and uses Ethernet Card addresses, nanoseconds, chip ID codes, and many possible numbers. The combination of the following parts: the current date and time (the first part of UUID is related to the time. If you generate a UUID in seconds, the first part is different and the rest are the same), the clock sequence, and the globally unique IEEE machine identification number (if there is a nic, it is obtained from the NIC, and no Nic is obtained in other ways ), the unique defect of UUID is that the generated result string is long. The most common UUID standard is Microsoft's GUID (Globals Unique Identifiers ).

GUID is a 128-bit long number, which is generally expressed in hexadecimal notation. The core idea of an algorithm is to combine the machine's Nic, local time, and a random number to generate a GUID. Theoretically, if a machine generates 10000000 guids per second, it can ensure (in probability) that there will be no duplicates in 3240.

UUID is a new class in 1.5. in java. util, it can generate a globally unique 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 );
}
}

 
The following methods are used to generate UUID in Java:

JDK1.5
If JDK is used, it is easy to generate a UUID, so that JDK implements the UUID:
Java. util. UUID, which can be called directly.
UUID uuid = UUID. randomUUID ();
String s = UUID. randomUUID (). toString (); // The primary key id used to generate the database is very good ..

UUID is composed of Sixteen digits.
550E8400-E29B-11D4-A716-446655440000

// The following code retrieves a unique primary key id for the database
Public class UUIDGenerator {
Public UUIDGenerator (){
}
/**
* Obtain a UUID
* @ Return String UUID
*/
Public static String getUUID (){
String s = UUID. randomUUID (). toString ();
// Remove the "-" symbol
Return s. substring () + s. substring () + s. substring (24 );
}
/**
* Obtain the specified UUID.
* @ Param number int the number of UUID to be obtained
* @ Return String [] UUID Array
*/
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]);
}
}
}


Two methods are used to generate guid and uuid

Comm log library required

/**
* @ Author Administrator
*
* TODO To change the template for this generated type comment go
* 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 ());
}
}


}

Similarly

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

 

This article from the CSDN blog, reproduced please indicate the source: http://blog.csdn.net/xiajing12345/archive/2005/04/22/358976.aspx

 

UUID stands for the universal Unique Identifier, which is a standard for Software construction and also known as the Open Software Foundation (OSF) is a part of the organization in the Distributed Computing Environment (Distributed Computing Environment, DCE) field. The purpose of UUID is to allow all elements in the distributed system to have unique identification information without specifying the identification information through the central control terminal. In this way, each user can create a UUID that does not conflict with others. In this case, duplicate names are not required during database creation. At present, the most widely used UUID is Microsoft's Globally Unique Identifiers (GUIDs, linux ext2/ext3 file system, LUKS encryption partition, GNOME, KDE, Mac OS X, and so on.

The following is an example of UUID generation:

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 ();
// Remove the "-" symbol
String temp = str. substring (0, 8) + str. substring (9, 13) + str. substring (14, 18) + str. substring (19, 23) + str. substring (24 );
Return str + "," + temp;
}
// Obtain the specified number of 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 ();
// Remove the "-" symbol
String temp = str. substring (0, 8) + str. substring (9, 13) + str. substring (14, 18) + str. substring (19, 23) + str. substring (24 );
Return str + "," + temp;
}
// Obtain the specified number of 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]);
}
}
}

Result:

View plaincopy to clipboardprint?
Ss [0] ==== 4cdbc040-657a-4847-b266-7e31d9e2c3d9, 4cdbc040657a4847b2667e31d9e2c3d9
Ss [1] ==== 72297c88-109-4c05-9b05-d28bfb11d10b, 72297c881094c059b05d28bfb11d10b
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, ddd4b5a9fe9806cbd7863b70bb500a1
Ss [0] ==== 4cdbc040-657a-4847-b266-7e31d9e2c3d9, 4cdbc040657a4847b2667e31d9e2c3d9
Ss [1] ==== 72297c88-109-4c05-9b05-d28bfb11d10b, 72297c881094c059b05d28bfb11d10b
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, ddd4b5a9fe9806cbd7863b70bb500a1

It can be seen that UUID refers to the number generated on a machine, which ensures that all machines in the same time and space are unique. Generally, the platform provides the generated API. According to the standards set by the Open Software Foundation (OSF), ethernet card addresses, nanoseconds, chip ID codes, and many possible numbers are used.

UUID consists of the following parts:

(1) The current date and time. The first part of UUID is related to the time. If you generate a UUID after several seconds and then generate a UUID, the first part is different, the rest are the same.

(2) Clock Sequence

(3) Globally Unique IEEE machine identification number. If there is a nic, it is obtained from the nic mac address, and no Nic is obtained in other ways.

The unique defect of UUID is that the generated result string is long. The most common UUID standard is Microsoft's GUID (Globals Unique Identifiers ). In ColdFusion, you can use the CreateUUID () function to generate a UUID in the format of xxxxxxxx-xxxx-xxxxxxxxxxxxxxxx (8-4-4-16 ), each x is a hexadecimal number in the range of 0-9 or a-f. The standard UUID format is: xxxxxxxx-xxxx-xxxxxx-xxxxxxxxxx (8-4-4-4-12). You can download CreateGUID () UDF from cflib for conversion.

The benefits of using UUID can be reflected in distributed software systems (such as DCE/RPC, COM +, and CORBA), which ensures that the IDS generated by each node are not repeated, with the development of integrated technologies such as WEB Services, the advantages of UUID will become more obvious. According to the specific mechanism used, UUID should not only ensure that they are different from each other, or at least it is very different from any other universal unique identifier generated before January 1, 3400 AD.

A universal unique identifier can also be used to point to most possible objects. Microsoft and some other software companies tend to use globally unique identifiers (GUID), a type of generic unique identifiers that can be used to point to object module objects and other software components. The first universal unique identifier is the component created in the networked computer system (NCS) and subsequently became the distributed computing environment (DCE) component of the Open Software Foundation (OSF.

 

This article from the CSDN blog, reproduced please indicate the source: http://blog.csdn.net/carefree31441/archive/2009/03/17/3998553.aspx

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.