1) 生成主鍵隨機數: 時間+隨機數
// package com.demo.utils;
import java.util.Random;
/**
* 生成主鍵隨機數
* 時間+++ 隨機數
* Created by hll on 2018/5/31.
*/
public class KeyUtil {
/**
* 生成唯一的主鍵
* 格式: 時間+隨機數
* @return
*/
public static synchronized String getKey() {
Random random = new Random();
Integer number = random.nextInt(900000) + 100000;//生成6位隨機數
return System.currentTimeMillis() + String.valueOf(number);
}
public static void main(String[] args){
System.out.println(getKey());
}
}
2)隨機字符/數工具類
package cn.uctimes.product.library.commons.utils;
/**
* 隨機字符/數工具類
*
* @author hezhuangzhuang
* @date 2018-01-07 16:18:02
*
*/
public class RandomUtil {
private static class RandomUtilHandler {
private static RandomUtil instance = new RandomUtil();
}
private RandomUtil() {
}
public static RandomUtil getInstance() {
return RandomUtilHandler.instance;
}
/**
* 生成小寫大寫數字混合的固定長度的隨機字符串
* @param length
* @return
*/
public String genMixString(int length) {
return genString(length,null);
}
/**
* 生成隨機字符串
* @param length
* @param type 0:只生成大寫字母,1只生成小寫字母,2:只生成數字,其他/null:混合類型
* @return
*/
public String genString(Integer length,Integer type){
if(null == length)
throw new RuntimeException("length can not be null");
char[] ss = new char[length];
int i = 0;
Integer f = type;
while (i < length) {
if(null == type )
f = (int) (Math.random() * 3);
if (f == 0)
ss[i] = (char) ('A' + Math.random() * 26);
else if (f == 1)
ss[i] = (char) ('a' + Math.random() * 26);
else if (f == 2)
ss[i] = (char) ('0' + Math.random() * 10);
else{
type = null;
continue;
}
i++;
}
String is = new String(ss);
return is;
}
public static void main(String[] args) {
System.out.println(RandomUtil.getInstance().genString(10, 0));
}
}