From 5a1ee1fd86b57ae28fcf76445f3ec1ec3d9c67e5 Mon Sep 17 00:00:00 2001 From: ZhouXY108 Date: Fri, 16 Jun 2023 02:40:47 +0800 Subject: [PATCH] =?UTF-8?q?=E5=88=9B=E5=BB=BA=20IdGenerator=EF=BC=8C?= =?UTF-8?q?=E5=B0=81=E8=A3=85=20SnowflakeId=E3=80=81UUID=20=E7=9A=84?= =?UTF-8?q?=E7=94=9F=E6=88=90=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../plusone/commons/util/IdGenerator.java | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 src/main/java/xyz/zhouxy/plusone/commons/util/IdGenerator.java diff --git a/src/main/java/xyz/zhouxy/plusone/commons/util/IdGenerator.java b/src/main/java/xyz/zhouxy/plusone/commons/util/IdGenerator.java new file mode 100644 index 0000000..5f88b36 --- /dev/null +++ b/src/main/java/xyz/zhouxy/plusone/commons/util/IdGenerator.java @@ -0,0 +1,61 @@ +package xyz.zhouxy.plusone.commons.util; + +import java.util.UUID; + +import com.google.common.annotations.Beta; +import com.google.common.collect.HashBasedTable; +import com.google.common.collect.Table; + +@Beta +public class IdGenerator { + + // ===== UUID ===== + + public static UUID newUuid() { + return UUID.randomUUID(); + } + + public static String uuidString() { + return UUID.randomUUID().toString(); + } + + public static String simpleUuidString() { + return toSimpleString(UUID.randomUUID()); + } + + public static String toSimpleString(UUID uuid) { + return (digits(uuid.getMostSignificantBits() >> 32, 8) + + digits(uuid.getMostSignificantBits() >> 16, 4) + + digits(uuid.getMostSignificantBits(), 4) + + digits(uuid.getLeastSignificantBits() >> 48, 4) + + digits(uuid.getLeastSignificantBits(), 12)); + } + + // ===== SnowflakeId ===== + + private static final Table snowflakePool = HashBasedTable.create(); + + public static long nextSnowflakeId(long workerId, long datacenterId) { + SnowflakeIdGenerator generator = snowflakePool.get(workerId, datacenterId); + if (generator == null) { + synchronized (IdGenerator.class) { + generator = snowflakePool.get(workerId, datacenterId); + if (generator == null) { + generator = new SnowflakeIdGenerator(workerId, datacenterId); + snowflakePool.put(workerId, datacenterId, generator); + } + } + } + return generator.nextId(); + } + + /** Returns val represented by the specified number of hex digits. */ + private static String digits(long val, int digits) { + long hi = 1L << (digits * 4); + return Long.toHexString(hi | (val & (hi - 1))).substring(1); + } + + private IdGenerator() { + throw new IllegalStateException("Utility class"); + } +}