|
@@ -0,0 +1,52 @@
|
|
|
+package com.uas.search.util;
|
|
|
+
|
|
|
+import java.util.Calendar;
|
|
|
+import java.util.Date;
|
|
|
+
|
|
|
+/**
|
|
|
+ * 生成唯一 code
|
|
|
+ *
|
|
|
+ * @author sunyj
|
|
|
+ * @since 2017年8月22日 上午11:34:44
|
|
|
+ */
|
|
|
+public class CodeGenerator {
|
|
|
+
|
|
|
+ private final static int MAX_OFFSET = 16 * 16 - 16;
|
|
|
+ /**
|
|
|
+ * 生成 code 时的偏移量
|
|
|
+ */
|
|
|
+ private static int offset = 0;
|
|
|
+ private static CodeGenerator generator;
|
|
|
+
|
|
|
+ private CodeGenerator() {
|
|
|
+ }
|
|
|
+
|
|
|
+ public static CodeGenerator getGenerator() {
|
|
|
+ if (generator == null) {
|
|
|
+ synchronized (CodeGenerator.class) {
|
|
|
+ if (generator == null) {
|
|
|
+ generator = new CodeGenerator();
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return generator;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 生成唯一 code (一秒内不超过 {@link CodeGenerator#MAX_OFFSET} 个,超过则不唯一)
|
|
|
+ */
|
|
|
+ public synchronized String generate() {
|
|
|
+ // 偏移量,不超过 MAX_OFFSET 个
|
|
|
+ offset = (offset + 1) % MAX_OFFSET + 16;
|
|
|
+ // 当前毫秒数
|
|
|
+ long now = new Date().getTime();
|
|
|
+ // 起始时间 2017-01-01 00:00:00:000
|
|
|
+ Calendar startCalendar = Calendar.getInstance();
|
|
|
+ startCalendar.set(2017, 0, 1, 0, 0, 0);
|
|
|
+ startCalendar.set(Calendar.MILLISECOND, 0);
|
|
|
+ // 偏移量加16,保证得到的是两位16进制字符
|
|
|
+ String hex = Long.toHexString(now - startCalendar.getTimeInMillis()) + Integer.toHexString(offset);
|
|
|
+ // 最后反转并转为大写
|
|
|
+ return hex.toUpperCase();
|
|
|
+ }
|
|
|
+}
|