在使用數(shù)據(jù)庫的時候,經(jīng)常需要生成主鍵,用過數(shù)據(jù)庫的自增長,但I(xiàn)D太有序了,很容易就能讓人知道下一條記錄的ID。也用過Hibernate的UUID生成,但生成的主鍵似乎又太長了點,于是想著自己寫一個工具來實現(xiàn)。
首先想到的便是用時間戳+隨機(jī)碼的方式,對于并發(fā)量不是特別特別特別高的情況來說,基本是夠用的,于是我一般都用Long.parseLong(""+(int)(Math.random()*100)+(new Date()).getTime()+(int)(Math.random()*100))的方式來生成一個Long型的值,但這個值一來太長了,二來很容易給人找出規(guī)律,畢竟時間戳部分的前幾位是一致的,于是考慮到將這個Long值轉(zhuǎn)成類似于16進(jìn)制之類的字符串。不過數(shù)字+字母(分大小寫)一共有62位,16進(jìn)制只用到了其中的一部分,還有大把沒用的,有點浪費。在參考了Long類的toHexString()方法源碼后,自己改寫了一個工具類。
package com.hing.tools;

import java.util.Date;

 /** *//**
* author:hingwu email:hing3@163.com QQ:550598 MSN:hing3wu@hotmail.com(很少開)
*
* 2007-3-28 上午11:40:18
*/
 public class MyLong ...{
public static final long MIN_VALUE = 0x8000000000000000L;

public static final long MAX_VALUE = 0x7fffffffffffffffL;

 final static char[] digits = ...{ ‘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‘, ‘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‘, ‘-‘, ‘_‘ };

 private static String toUnsignedString(long i, int shift) ...{
char[] buf = new char[64];
int charPos = 64;
int radix = 1 << shift;
long mask = radix - 1;
 do ...{
buf[--charPos] = digits[(int) (i & mask)];
i >>>= shift;
} while (i != 0);
return new String(buf, charPos, (64 - charPos));
}
// j為2的次方,如轉(zhuǎn)成16進(jìn)制就是4,32進(jìn)制就是5...
 public static String getRand(long i,int j)...{
return toUnsignedString(i, j);
}
// 隨機(jī)碼+時間戳+隨機(jī)碼的生成
 public static Long getRand()...{
String str1,str2,str3;
str1=getRandStr(2);
str3=getRandStr(3);
str2=(new Date()).getTime()+"";
//System.out.println(str1+str2+str3);
return Long.parseLong(str1+str2+str3);
}
// 主鍵生成
 public static String getKey()...{
return getRand(getRand(),6);
}
// 生成指定長度的隨機(jī)串
 public static String getRandStr(Integer length)...{
String str="";
 while(str.length()!=length)...{
str=(Math.random()+"").substring(2,2+length);
}
return str;
}
}

測試類:
package com.test;

import java.util.Date;

import com.hing.tools.MyLong;



 /** *//**
* author:hingwu
* email:hing3@163.com
* QQ:550598
* MSN:hing3wu@hotmail.com(很少開)
*
* 2007-3-15 下午04:37:26
*/
 public class Test ...{

 /** *//**
* @param args
* @throws IOException
* @throws InterruptedException
*/
 public static void main(String[] args)...{
// TODO Auto-generated method stub
 for(int i=0;i<10;i++)...{
System.out.println("第"+i+"個:"+MyLong.getKey());
}

}
}


測試結(jié)果:
第0個:qK43fCDV 第1個:KCAZxkKE4 第2個:47knOADSDV 第3個:lKZzvVmDQ 第4個:4RweI2I-Ek 第5個:3eup9odSEr 第6個:5p1ZROteDU 第7個:bN0kVHKgP 第8個:2lEqwbPSDE 第9個:7xtVcOSEh
如果把digits中的字符順序打亂的話,就更難給人找到規(guī)律了。
|