Java生成全局唯一流水号

在开发中,通常会遇到需要生成全局唯一的流水号的情况,用来标识某个实体或者操作的唯一性。在Java中,我们可以通过不同的方式来实现生成全局唯一流水号的功能,比如使用UUID、Snowflake算法等。本文将介绍一种基于Snowflake算法的方式来生成全局唯一流水号,并提供代码示例。

Snowflake算法简介

Snowflake算法是Twitter开发的一种分布式唯一ID生成算法,它可以生成一个64位的ID,其中包括了时间戳、机器ID和序列号。具体的组成结构如下:

  • 1位标志位:始终为0
  • 41位时间戳:表示生成ID的时间戳,精确到毫秒
  • 10位机器ID:表示机器的唯一ID,可以部署多台机器时区分
  • 12位序列号:表示同一毫秒内生成的ID的序号

Snowflake算法的优点是生成的ID按时间有序,并且在分布式环境下可以保证唯一性。

实现方法

下面我们通过Java代码来实现基于Snowflake算法的全局唯一流水号生成器。

public class SnowflakeIdGenerator {

    private final long twepoch = 1288834974657L; // 起始时间戳

    private final long workerIdBits = 5L;
    private final long datacenterIdBits = 5L;
    private final long sequenceBits = 12L;

    private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
    private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);

    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 SnowflakeIdGenerator(long workerId, long datacenterId) {
        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException(String.format("Worker ID must be between 0 and %d", maxWorkerId));
        }
        if (datacenterId > maxDatacenterId || datacenterId < 0) {
            throw new IllegalArgumentException(String.format("Datacenter ID must be between 0 and %d", maxDatacenterId));
        }
        this.workerId = workerId;
        this.datacenterId = datacenterId;
    }

    public synchronized long nextId() {
        long timestamp = timeGen();

        if (timestamp < lastTimestamp) {
            throw new RuntimeException("Clock moved backwards. Refusing to generate ID");
        }

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

        lastTimestamp = timestamp;

        return ((timestamp - twepoch) << timestampLeftShift)
                | (datacenterId << datacenterIdShift)
                | (workerId << workerIdShift)
                | sequence;
    }

    private long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    private long timeGen() {
        return System.currentTimeMillis();
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.

使用示例

我们可以通过创建SnowflakeIdGenerator对象,传入不同的workerIddatacenterId来生成全局唯一流水号。

public class Main {
    public static void main(String[] args) {
        SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1, 1);
        long id = idGenerator.nextId();
        System.out.println("Generated ID: " + id);
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

总结

通过以上示例,我们学习了如何使用Snowflake算法来生成全局唯一流水号,保证了分布式环墓下的唯一性和有序性。在实际开发中,我们可以根据实际情况调整算法的参数,比如workerIddatacenterId的位数,以适应不同规模的分布式系统。希