Browse Source

雪花id新增反解时间戳方法

miemie 2 years ago
parent
commit
ceddb5164c

+ 17 - 1
mybatis-plus-core/src/main/java/com/baomidou/mybatisplus/core/toolkit/Sequence.java

@@ -37,7 +37,7 @@ public class Sequence {
     /**
      * 时间起始标记点,作为基准,一般取系统的最近时间(一旦确定不能变动)
      */
-    private final long twepoch = 1288834974657L;
+    private static final long twepoch = 1288834974657L;
     /**
      * 机器标识位数
      */
@@ -199,4 +199,20 @@ public class Sequence {
         return SystemClock.now();
     }
 
+    /**
+     * 反解id的时间戳部分
+     */
+    public static long parseIdTimestamp(long id) {
+        String s = Long.toBinaryString(id);
+        int x = 64 - s.length();
+        StringBuilder b = new StringBuilder();
+        for (int i = 0; i < x; i++) {
+            b.append("0");
+        }
+        s = b + s;
+        s = s.substring(1, 42);
+        long l = Long.parseUnsignedLong(s, 2);
+        l += twepoch;
+        return l;
+    }
 }

+ 31 - 0
mybatis-plus-core/src/test/java/com/baomidou/mybatisplus/core/toolkit/SequenceTest.java

@@ -0,0 +1,31 @@
+package com.baomidou.mybatisplus.core.toolkit;
+
+import org.junit.jupiter.api.Test;
+
+import java.time.Instant;
+import java.time.LocalDateTime;
+import java.time.ZoneId;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * @author miemie
+ * @since 2022-10-17
+ */
+class SequenceTest {
+
+    @Test
+    void nextId() {
+        Sequence sequence = new Sequence(null);
+        long id = sequence.nextId();
+        LocalDateTime now = LocalDateTime.now();
+        System.out.println(sequence.nextId() + "---" + now);
+
+        long timestamp = Sequence.parseIdTimestamp(id);
+        Instant instant = Instant.ofEpochMilli(timestamp);
+        ZoneId zone = ZoneId.systemDefault();
+        LocalDateTime time = LocalDateTime.ofInstant(instant, zone);
+        System.out.println(timestamp + "---" + time);
+        assertThat(now).isAfter(time);
+    }
+}