public class IdGenerator { private static volatile Snowflake snowflake = new Snowflake(); public static synchronized String nextId() { return String.valueOf(snowflake.nextId()); } private static class Snowflake { private static final long START_TIME = 1672502400000L; // 22023-01-01 00:00:00 UTC private static final int DATA_CENTER_ID_BITS = 5; private static final int MACHINE_ID_BITS = 5; private static final int SEQUENCE_BITS = 12; private static final int MAX_DATA_CENTER_ID = ~(-1 << DATA_CENTER_ID_BITS); private static final int MAX_MACHINE_ID = ~(-1 << MACHINE_ID_BITS); private static final int MAX_SEQUENCE = ~(-1 << SEQUENCE_BITS); private static final int MACHINE_ID_SHIFT = SEQUENCE_BITS; private static final int DATA_CENTER_ID_SHIFT = SEQUENCE_BITS + MACHINE_ID_BITS; private static final int TIMESTAMP_SHIFT = SEQUENCE_BITS + MACHINE_ID_BITS + DATA_CENTER_ID_BITS; private final int dataCenterId = 6; private final int machineId = 8; private long lastTimestamp = -1L; private int sequence = 0; public synchronized long nextId() { long timestamp = System.currentTimeMillis(); if (timestamp < lastTimestamp) { throw new RuntimeException("Clock moved backwards, refusing to generate ID"); } if (timestamp == lastTimestamp) { sequence = (sequence + 1) & MAX_SEQUENCE; if (sequence == 0) { // Sequence exhausted, wait for the next millisecond timestamp = waitNextMillis(timestamp); } } else { sequence = 0; } lastTimestamp = timestamp; return ((timestamp - START_TIME) << TIMESTAMP_SHIFT) | (dataCenterId << DATA_CENTER_ID_SHIFT) | (machineId << MACHINE_ID_SHIFT) | sequence; } private long waitNextMillis(long timestamp) { while (timestamp == lastTimestamp) { timestamp = System.currentTimeMillis(); } return timestamp; } } }
文章来源地址https://www.toymoban.com/news/detail-433811.html
文章来源:https://www.toymoban.com/news/detail-433811.html
到了这里,关于雪花算法生成唯一数字id的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!