|
@@ -0,0 +1,37 @@
|
|
|
|
+package com.backendsys.utils;
|
|
|
|
+
|
|
|
|
+import com.backendsys.exception.CustomException;
|
|
|
|
+
|
|
|
|
+import java.util.Calendar;
|
|
|
|
+import java.util.Random;
|
|
|
|
+
|
|
|
|
+public class IDUtil {
|
|
|
|
+
|
|
|
|
+ /**
|
|
|
|
+ * 将用户ID、日期和随机数结合起来生成一个10位的唯一数字
|
|
|
|
+ * IDUtil.generateUniqueID(4L, 10);
|
|
|
|
+ * - ID: 唯一主键
|
|
|
|
+ * - digits: 长度 (一般是10位,不能小于6位)
|
|
|
|
+ */
|
|
|
|
+ public static long generateUniqueID(long ID, int digits) {
|
|
|
|
+ // 获取当前日期的年月日作为数字的一部分
|
|
|
|
+ Calendar calendar = Calendar.getInstance();
|
|
|
|
+ int year = calendar.get(Calendar.YEAR) % 100; // 取最近100年,例如2024取24
|
|
|
|
+ int month = calendar.get(Calendar.MONTH) + 1; // 月份从1开始
|
|
|
|
+ int day = calendar.get(Calendar.DAY_OF_MONTH);
|
|
|
|
+
|
|
|
|
+ // 拼接日期和用户ID (5位)
|
|
|
|
+ long baseNumber = year * 10000 + month * 100 + day * ID;
|
|
|
|
+
|
|
|
|
+ // 预留4位给日期+ID的计算 (10的4次方)
|
|
|
|
+ if (digits < 6) throw new CustomException("(IDUtil.generateUniqueID) digits 不能小于 6");
|
|
|
|
+ Integer length = (int) Math.pow(10, (digits - 6));
|
|
|
|
+
|
|
|
|
+ // 生成4位随机数作为序列号,确保在同一天同一用户不会产生重复
|
|
|
|
+ Random random = new Random();
|
|
|
|
+ int randomPart = random.nextInt(length);
|
|
|
|
+ // 将所有部分组合起来形成最终的10位唯一数字
|
|
|
|
+ return baseNumber * length + randomPart;
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+}
|