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

74 lines
1.8 KiB
Java
Raw Normal View History

2024-03-11 16:28:36 +08:00
package com.ruoyi.web.utils;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
public class IdUtils {
/**
* 生成永不重复的订单号
* @param startLetter 订单号开头字符串
* @param size 订单号中随机的大写字母个数
* @return
*/
public static String createOrderNo(String startLetter,int size){
String orderNo = null;
Date nowDate = new Date();
Random random = new Random();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
//生成两位大写字母
String keyArr = randomLetter(size);
String fourRandom = random.nextInt(9999) + "";
int randLength = fourRandom.length();
//四位随机数不足四位的补0
if(fourRandom.length()<4){//不足四位的随机数补充0
for(int i=1; i<=4-randLength; i++){
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;
}
/**
* 测试
* @param args
*/
public static void main(String[] args) {
System.out.println(createOrderNo("PO_",2));
}
}