编写后台程序时候总要涉及到用户的注册,用户注册的时候往往会随机生成一个用户id,毫无疑问,用户id就像人的身份证号一样不能重复。实现的方法:当前毫秒数+三位随机数(数字+字母)。在同一秒内注册,并且生成的随机数的一样的概率非常低。
/**
* 生成普通用户uid:u+当前毫秒数+三位随机数
* @return
* */
public static String createUid(){
long time=System.currentTimeMillis();
String s=getCharAndNumr(3);
return "u"+time+s;
}
/**
* java生成随机数字和字母组合
*
* @param length[生成随机数的长度]
* @return
*/
public static String getCharAndNumr(int length) {
String val = "";
Random random = new Random();
for (int i = 0; i < length; i++) {
// 输出字母还是数字
String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
// 字符串
if ("char".equalsIgnoreCase(charOrNum)) {
// 取得大写字母还是小写字母
int choice = random.nextInt(2) % 2 == 0 ? 65 : 97;
val += (char) (choice + random.nextInt(26));
} else if ("num".equalsIgnoreCase(charOrNum)) { // 数字
val += String.valueOf(random.nextInt(10));
}
}
return val;
}