项目中使用UUID作为主键,但无论是mysql生成的UUID还是java的randomUUID都是无序的,很不方便查看数据的生成顺序,这里写了一个有序UUID的生成类,使用起来十分方便,而且可以按照生成时间进行排序,生成方法简单高效,方便使用者再次基础上进行扩展。
package app.core.util;
import java.net.InetAddress;
import java.util.UUID;
/**
*
* @author Beyound
*
*/
public class UtilUUID{
private static final String sep = "-";
public static String generate() {
return format(System.currentTimeMillis())+"-"+
format(System.currentTimeMillis()>>4)+ "-"+format(getIP())+"-"+ formatInt( getCount());
}
public static void main(String[] args) {
UUID.randomUUID().toString();
System.out.println(generate());
// System.out.println(format());
}
protected static String format(int value) {
int index = value%chars.length;
value = value/chars.length;
if(value>0){
return format(value)+chars[index];
}else return ""+chars[index];
}
protected static String formatInt(int value) {
String re = format(value);
re="000000"+re;
return re.substring(re.length()-7);
}
static char[] chars = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g',
'h','i','j','k','l','m','n',
'o','p','q','r','s','t',
'u','v','w','x','y','z'};
public static String format(Long value){
Long index = value%chars.length;
value = value/chars.length;
if(value>0){
return format(value)+chars[index.intValue()];
}else return ""+chars[index.intValue()];
}
public static int toInt(byte[] bytes) {
int result = 0;
for ( int i = 0; i < 4; i++ ) {
result = ( result << 8 ) - Byte.MIN_VALUE + (int) bytes[i];
}
return result;
}
private static final int IP;
static {
int ipadd;
try {
ipadd = toInt( InetAddress.getLocalHost().getAddress() );
}
catch (Exception e) {
ipadd = 0;
}
IP = ipadd;
}
private static Integer counter = (Integer) 0;
private static final int JVM = (int) ( System.currentTimeMillis() >>> 8 );
protected static Integer getCount() {
synchronized(UtilUUID.class) {
return counter=counter<0?0:++counter;
}
}
protected static int getIP() {
return IP;
}
}