javacodeadmin/ruoyi-system/src/main/java/com/ruoyi/system/controllerUtil/GenerateCustomCode.java

42 lines
1.4 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.ruoyi.system.ControllerUtil;
import java.util.Random;
public class GenerateCustomCode {
/**
* 生成自定义前缀+16位唯一数字码
* 例如FEEB724145038871780
* @param prefix 前缀字母可为null或空自动生成4位大写字母
* @return 生成的码
*/
public static String generCreateOrder(String prefix) {
// 生成前缀
String codePrefix = prefix;
if (codePrefix == null || codePrefix.trim().isEmpty()) {
// 随机生成4位大写字母
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < 4; i++) {
char c = (char) ('A' + random.nextInt(26));
sb.append(c);
}
codePrefix = sb.toString();
}
// 生成16位唯一数字
// 用当前时间戳+3位随机数保证唯一性和随机性
long timestamp = System.currentTimeMillis();
String timePart = String.valueOf(timestamp);
// 补足到16位
StringBuilder numberPart = new StringBuilder(timePart);
Random random = new Random();
while (numberPart.length() < 16) {
numberPart.append(random.nextInt(10));
}
// 如果超出16位则截取
String finalNumber = numberPart.substring(0, 16);
return codePrefix + finalNumber;
}
}