JNBusiness/ruoyi-admin/src/main/java/com/ruoyi/web/utils/IdUtils.java

113 lines
3.0 KiB
Java
Raw Normal View History

2024-03-11 16:28:36 +08:00
package com.ruoyi.web.utils;
2024-04-01 11:13:35 +08:00
import com.ruoyi.common.utils.uuid.UUID;
2024-03-11 16:28:36 +08:00
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
public class IdUtils {
2024-04-01 11:13:35 +08:00
/***********************************************生成永不重复的单号*********************************************/
2024-03-11 16:28:36 +08:00
/**
2024-04-01 11:13:35 +08:00
* 生成永不重复的单号
2024-03-11 16:28:36 +08:00
* @param startLetter 订单号开头字符串
* @param size 订单号中随机的大写字母个数
* @return
*/
2024-03-26 15:56:53 +08:00
public static String createNo(String startLetter,int size){
2024-03-11 16:28:36 +08:00
String orderNo = null;
Date nowDate = new Date();
Random random = new Random();
2024-03-27 10:34:49 +08:00
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
2024-03-11 16:28:36 +08:00
//生成两位大写字母
String keyArr = randomLetter(size);
2024-03-27 14:08:55 +08:00
String fourRandom = random.nextInt(999) + "";
2024-03-11 16:28:36 +08:00
int randLength = fourRandom.length();
//四位随机数不足四位的补0
2024-03-27 14:08:55 +08:00
if(fourRandom.length()<3){//不足四位的随机数补充0
for(int i=1; i<=3-randLength; i++){
2024-03-11 16:28:36 +08:00
fourRandom = '0' + fourRandom;
}
}
orderNo=startLetter+keyArr+sdf.format(nowDate)+fourRandom;
return orderNo;
}
/**
* 生成大写字母
* @param size
* @return
*/
public static String randomLetter(int size){
String keyArr= "";
char key = 0;
boolean[] flag=new boolean[26]; //定义一个Boolean型数组用来除去重复值
for(int i=0;i<size;i++){ //通过循环为数组赋值
Random rand=new Random();
int index;
do{
index=rand.nextInt(26); //随机生成0-25的数字并赋值给index
}while(flag[index]); //判断flag值是否为true,如果为true则重新为index赋值
key=(char) (index+65); //大写字母的ASCII值为65-90所以给index的值加上65使其符合大写字母的ASCII值区间
flag[index]=true; //让对应的flag值为true
keyArr +=key;
}
return keyArr;
}
2024-04-01 11:13:35 +08:00
/***********************************************生成永不重复的单号*********************************************/
/***********************************************获取随机UUID*********************************************/
/**
* 获取随机UUID
*
* @return 随机UUID
*/
public static String randomUUID()
{
return UUID.randomUUID().toString();
}
/**
* 简化的UUID去掉了横线
*
* @return 简化的UUID去掉了横线
*/
public static String simpleUUID()
{
return UUID.randomUUID().toString(true);
}
/**
* 获取随机UUID使用性能更好的ThreadLocalRandom生成UUID
*
* @return 随机UUID
*/
public static String fastUUID()
{
return UUID.fastUUID().toString();
}
/**
* 简化的UUID去掉了横线使用性能更好的ThreadLocalRandom生成UUID
*
* @return 简化的UUID去掉了横线
*/
public static String fastSimpleUUID()
{
return UUID.fastUUID().toString(true);
}
/***********************************************获取随机UUID*********************************************/
2024-03-11 16:28:36 +08:00
/**
* 测试
* @param args
*/
public static void main(String[] args) {
2024-03-26 15:56:53 +08:00
System.out.println(createNo("PO_",2));
2024-03-11 16:28:36 +08:00
}
}