GUID是一个128位长的数字,一般用16进制表示。算法的核心思想是结合机器的网卡、当地时间、一个随即数来生成GUID。从理论上讲,如果一台机器每秒产生10000000个GUID,则可以保证(概率意义上)3240年不重复。
package com.cn.str;
import java.util.UUID;
/**
* Create GUID
* @author Administrator
*
*/
public class CreateGUID {
public static final String GenerateGUID(){
UUID uuid = UUID.randomUUID();
return uuid.toString();
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(GenerateGUID());
}
}
UUID是1.5中新增的一个类,在java.util下,用它可以产生一个号称全球唯一的ID
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