我们创建一个类 叫 SnowflakeIdGenerator 作为生成雪花id的工具类
然后 编写代码如下

public class SnowflakeIdGenerator {
    private static final long START_TIMESTAMP = 1609459200000L; // 设置起始时间戳,可以根据需要进行调整
    private static final long WORKER_ID_BITS = 5L; // 机器ID所占位数
    private static final long DATACENTER_ID_BITS = 5L; // 数据中心ID所占位数
    private static final long SEQUENCE_BITS = 12L; // 序列号所占位数

    private static final long MAX_WORKER_ID = ~(-1L << WORKER_ID_BITS); // 机器ID的最大值
    private static final long MAX_DATACENTER_ID = ~(-1L << DATACENTER_ID_BITS); // 数据中心ID的最大值

    private static final long WORKER_ID_SHIFT = SEQUENCE_BITS; // 机器ID的位移量
    private static final long DATACENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS; // 数据中心ID的位移量
    private static final long TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATACENTER_ID_BITS; // 时间戳的位移量

    private static final long SEQUENCE_MASK = ~(-1L << SEQUENCE_BITS); // 序列号的屏蔽位

    private final long workerId; // 机器ID
    private final long datacenterId; // 数据中心ID
    private long lastTimestamp = -1L; // 上次生成ID的时间戳
    private long sequence = 0L; // 序列号

    public SnowflakeIdGenerator(long workerId, long datacenterId) {
        if (workerId > MAX_WORKER_ID || workerId < 0) {
            throw new IllegalArgumentException("Worker ID 超出范围");
        }
        if (datacenterId > MAX_DATACENTER_ID || datacenterId < 0) {
            throw new IllegalArgumentException("数据中心 ID 超出范围");
        }
        this.workerId = workerId;
        this.datacenterId = datacenterId;
    }

    public synchronized long nextId() {
        long timestamp = System.currentTimeMillis();

        if (timestamp < lastTimestamp) {
            throw new RuntimeException("系统时间不正确");
        }

        if (timestamp == lastTimestamp) {
            sequence = (sequence + 1) & SEQUENCE_MASK;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }

        lastTimestamp = timestamp;

        return ((timestamp - START_TIMESTAMP) << TIMESTAMP_LEFT_SHIFT) |
                (datacenterId << DATACENTER_ID_SHIFT) |
                (workerId << WORKER_ID_SHIFT) |
                sequence;
    }

    private long tilNextMillis(long lastTimestamp) {
        long timestamp = System.currentTimeMillis();
        while (timestamp <= lastTimestamp) {
            timestamp = System.currentTimeMillis();
        }
        return timestamp;
    }
}

然后 只需要在其他类中调用他 获取id即可

SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1, 1);
long id = idGenerator.nextId();
System.out.println("新的雪花ID:" + id);

这里 我们直接new了一个SnowflakeIdGenerator类的实例
然后 通过nextId获取一个雪花id
运行结果如下
java写一个用于生成雪花id的工具类-LMLPHP
也是没有任何问题

09-17 12:11