算法生成的ID结构
- 一个符号位,永远是0;
- 41bit的毫秒数
- 10bit作为机器ID(5bit是数据中心,5bit是机器ID)
- 12bit序列号
- 最高位是符号位,正数是0,负数是1,所以id一般是正数,最高位是0
- 41位时间截不是存储当前时间的时间截,而是存储时间截的差值(当前时间截 - 开始时间截)
算法代码
public class SnowflakeIdWorker {
private final long twepoch = 1565020800000L;
private final long workerIdBits = 5L;
private final long datacenterIdBits = 5L;
private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
private final long sequenceBits = 12L;
private final long workerIdShift = sequenceBits;
private final long datacenterIdShift = sequenceBits + workerIdBits;
private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
private final long sequenceMask = -1L ^ (-1L << sequenceBits);
private long workerId;
private long datacenterId;
private long sequence = 0L;
private long lastTimestamp = -1L;
public SnowflakeIdWorker(long workerId, long datacenterId) {
if (workerId > maxWorkerId || workerId < 0) {
throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
}
if (datacenterId > maxDatacenterId ||