import java.util.Date;
import java.util.Random;
public class IDUtils {
private static int seq = 0;//序列
private static final int LIMIT = 100000;//上限
private static Date date = new Date();
/**
* 图片名生成
*/
public static String genImageName() {
//取当前时间的长整形值包含毫秒
long millis = System.currentTimeMillis();
//long millis = System.nanoTime();
//加上三位随机数
Random random = new Random();
int end3 = random.nextInt(999);
//如果不足三位前面补0
String str = millis + String.format("%03d", end3);
return str;
}
/**
* 商品id生成
*/
public static long genItemId() {
//取当前时间的长整形值包含毫秒
long millis = System.currentTimeMillis();
//long millis = System.nanoTime();
//加上两位随机数
Random random = new Random();
int end2 = random.nextInt(99);
//如果不足两位前面补0
String str = millis + String.format("%02d", end2);
long id = new Long(str);
return id;
}
/**
* 生成编号
* @param number 生成的编号位数
* @return 返回生成的随机数
*/
public static long randomNo(int number){
double rate1 = Math.pow(10,number-1);
double rate2 = rate1*9;
long rate3 = (long)rate1*10;
Random random = new Random();
double tmp= random.nextDouble()*rate2+rate1;
long no = Math.round(tmp)%rate3;
return no;
}
//根据时间生成唯一编码(考虑并发)
public static synchronized long timeUinqueNumber(){
if (seq > LIMIT) seq = 0;
date.setTime(System.currentTimeMillis());
String str = String.format("%1$tY%1$tm%1$td%1$tk%1$tM%1$tS%2$05d", date, seq++);
return Long.parseLong(str);
}
/**
* 生成唯一的主键
* 格式: 时间+随机数
* @return
*/
public static synchronized String genUniqueKey() {
Random random = new Random();
Integer number = random.nextInt(900000) + 100000;
return System.currentTimeMillis() + String.valueOf(number);
}
public static void main(String[] args) {
System.out.println(genItemId());
System.out.println(genImageName());
System.out.println(randomNo(11));
System.out.println(timeUinqueNumber());
}
}
ID自动生成工具
最新推荐文章于 2024-08-31 23:00:49 发布