您的位置:

Snowflake ID详解

一、什么是Snowflake ID

Snowflake ID是Twitter开源的基于时间戳生成唯一ID的算法,它通过将一个64位的长整型分为四部分,每部分分别表示不同信息组成,从而保证了生成的ID的唯一性。

这四个部分依次是:1位符号位(始终为0),41位时间戳(精确到毫秒),10位工作机器ID和12位序列号。

具体而言,每一个Snowflake ID是由以下四个部分组成的:

  • 1位符号位(始终为0)
  • 41位时间戳(精确到毫秒)
  • 10位工作机器ID(可指定多台机器采用不同ID)
  • 12位序列号(防止同一毫秒内生成的ID重复)

在实际应用中,程序员可以根据需要对时间戳、工作机器ID和序列号进行自定义。

二、Snowflake Id Worker

Snowflake Id Worker是一个类,用于生成和解析Snowflake ID。

public class SnowflakeIdWorker {
    
    private final long workerId;
    private final long epoch = 1288834974657L;
    private final long workerIdBits = 5L;
    private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
    private final long sequenceBits = 12L;
    private final long workerIdShift = sequenceBits;
    private final long timestampLeftShift = sequenceBits + workerIdBits;
    private final long sequenceMask = -1L ^ (-1L << sequenceBits);
    private long lastTimestamp = -1L;
    private long sequence = 0L;

    public SnowflakeIdWorker(long workerId) {
        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
        }
        this.workerId = workerId;
    }

    public synchronized long nextId() {
        long timestamp = System.currentTimeMillis();
        if (timestamp < lastTimestamp) {
            throw new RuntimeException(String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
        }
        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & sequenceMask;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }
        lastTimestamp = timestamp;
        return ((timestamp - epoch) << timestampLeftShift) | (workerId << workerIdShift) | sequence;
    }

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

上述代码中,workerId代表工作机器ID,只需要设置一次;lastTimestamp和sequence分别记录上一次生成ID的时间戳和序列号;epoch代表起始时间(默认为Thu, 04 Nov 2010 01:42:54 GMT)。

三、Snowflake Id Factory

Snowflake Id Factory是一个基于Snowflake ID生成器的工厂类,主要用于创建和管理Snowflake ID生成器。

public class SnowflakeIdFactory {

    private final Map workerMap = new ConcurrentHashMap<>();

    public SnowflakeIdWorker getSnowflakeIdWorker(long workerId) {
        return workerMap.computeIfAbsent(workerId, id -> new SnowflakeIdWorker(id));
    }
}

  

上面的代码中,workerMap是一个ConcurrentHashMap,用于存储WorkerId和SnowflakeIdWorker之间的映射关系;getSnowflakeIdWorker方法则用于创建并返回相应的SnowflakeIdWorker对象。

四、Snowflake Id Generator

Snowflake Id Generator是使用Snowflake ID的工具类,用于生成唯一的ID。

public class SnowflakeIdGenerator {
    
    private static final SnowflakeIdFactory FACTORY = new SnowflakeIdFactory();
    
    public static long nextId(long workerId) {
        SnowflakeIdWorker worker = FACTORY.getSnowflakeIdWorker(workerId);
        return worker.nextId();
    }
}

在上述代码中,nextId方法接受一个workerId参数,并使用SnowflakeIdWorker生成唯一的ID。

五、Snowflake Id在分布式系统中的应用

在分布式系统中,为了保证在不同的节点上生成唯一的ID,需要对Snowflake ID算法进行调整。通常的做法是,使用ZooKeeper来分配不同的workerId,并使用Redis或其他共享存储来记录各个worker的生成序列号。

下面是一个基于Redis的Snowflake生成器示例:

public class RedisSnowflakeIdWorker {

    private final long workerId;
    private final SnowflakeIdFactory idFactory;
    private final JedisPool jedisPool;
    private final String redisKey = "snowflake:id";
    private volatile long sequence = 0L;

    public RedisSnowflakeIdWorker(long workerId, JedisPool jedisPool) {
        this.workerId = workerId;
        this.idFactory = new SnowflakeIdFactory();
        this.jedisPool = jedisPool;
        init();
    }

    private void init() {
        try (Jedis jedis = jedisPool.getResource()) {
            if (!jedis.exists(redisKey)) {
                jedis.set(redisKey, "1");
            }
            sequence = Long.parseLong(jedis.get(redisKey));
        }
    }

    public synchronized long nextId() {
        long timestamp = System.currentTimeMillis();
        if (sequence >= (1 << 12)) {
            try (Jedis jedis = jedisPool.getResource()) {
                long current = Long.parseLong(jedis.get(redisKey));
                if (current > sequence) {
                    sequence = current;
                } else {
                    jedis.incr(redisKey);
                    sequence = Long.parseLong(jedis.get(redisKey));
                }
            }
        }
        SnowflakeIdWorker worker = idFactory.getSnowflakeIdWorker(workerId);
        return worker.nextId() + sequence;
    }
}

在上述代码中,RedisSnowflakeIdWorker继承了SnowflakeIdWorker类,通过Redis来维护sequence序列号,实现了分布式环境下的唯一ID生成器。