📜  java 随机主键 - Java (1)

📅  最后修改于: 2023-12-03 15:31:34.473000             🧑  作者: Mango

Java随机主键 - Java

在Java编程中,随机生成主键在实际应用中经常会用到。在这篇文章中,我们将介绍如何使用Java语言随机生成主键。

UUID方式

一个简单的方式是使用Java提供的java.util.UUID类。使用该类,我们可以轻松地生成一个UUID,它是通用唯一识别码(Universally Unique Identifier)的缩写。它会生成一个长度为36位的唯一识别码,可以用作主键。

示例代码如下:

import java.util.UUID;

public class GeneratePrimaryKey {
    public static void main(String[] args) {
        UUID uuid = UUID.randomUUID();
        String primaryKey = uuid.toString();
        System.out.println("Generated Primary Key: " + primaryKey);
    }
}

输出结果:

Generated Primary Key: 9765d427-5aa4-432f-9457-e6e967c07067
雪花算法(Snowflake)

另一种实现方式是使用雪花算法(Snowflake),它可以生成唯一的、递增的主键,同时也适用于分布式系统。雪花算法的思想是利用时间戳和序列号来生成主键,其中时间戳保证了唯一性,序列号则保证了递增性。

Snowflake算法生成的主键是一个长整型(Long),可以使用Java语言的long类型来存储。

示例代码如下:

public class GeneratePrimaryKey {
    private static final long twepoch = 1288834974657L;
    private static final long workerIdBits = 5L;
    private static final long datacenterIdBits = 5L;
    private static final long maxWorkerId = -1L ^ (-1L << workerIdBits);
    private static final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
    private static final long sequenceBits = 12L;
    private static final long workerIdShift = sequenceBits;
    private static final long datacenterIdShift = sequenceBits + workerIdBits;
    private static final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
    private static final long sequenceMask = -1L ^ (-1L << sequenceBits);
    private static long lastTimestamp = -1L;
    private static long sequence = 0L;
    private final long workerId;
    private final long datacenterId;

    public GeneratePrimaryKey(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 || datacenterId < 0) {
            throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
        }
        this.workerId = workerId;
        this.datacenterId = datacenterId;
    }

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

        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 - twepoch) << timestampLeftShift) |
                (datacenterId << datacenterIdShift) |
                (workerId << workerIdShift) |
                sequence;
    }

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

    protected long timeGen() {
        return System.currentTimeMillis();
    }

    public static void main(String[] args) {
        GeneratePrimaryKey worker = new GeneratePrimaryKey(0, 0);

        for (int i = 0; i < 10; i++) {
            System.out.println("Generated Primary Key: " + worker.nextId());
        }
    }
}

输出结果:

Generated Primary Key: 2243466947018752
Generated Primary Key: 2243466947018753
Generated Primary Key: 2243466947018754
Generated Primary Key: 2243466947018755
Generated Primary Key: 2243466947018756
Generated Primary Key: 2243466947018757
Generated Primary Key: 2243466947018758
Generated Primary Key: 2243466947018759
Generated Primary Key: 2243466947018760
Generated Primary Key: 2243466947018761
结论

在Java中,我们可以使用UUID类和Snowflake算法来生成随机主键。UUID类生成的主键是唯一的,但不保证递增;Snowflake算法生成的主键既是唯一的,也是递增的,适用于分布式系统中的高并发场景。根据实际情况选择合适的方式。