揭秘Java中保证ID唯一性的5大高招,告别重复烦恼!

在Java开发中,保证ID的唯一性是一个常见且重要的需求。无论是数据库主键、分布式系统中的唯一标识符,还是其他场景下的唯一性校验,正确处理ID的唯一性可以避免数据冲突和系统错误。以下将详细介绍五种在Java中保证ID唯一性的高招。
高招一:使用UUID
UUID(Universally Unique Identifier)是一种广泛使用的唯一标识符生成方式。Java提供了
java.util.UUID
类来生成UUID。
import java.util.UUID;

public class UniqueIdGenerator {
public static String generateUUID() {
return UUID.randomUUID().toString();
}

public static void main(String[] args) {
String uniqueId = generateUUID();
System.out.println(“Generated UUID: ” + uniqueId);
}
}
UUID的优点是几乎全球范围内唯一,但它长度较长,不适合作为数据库的主键。
高招二:数据库自增主键
在关系型数据库中,自增主键是保证ID唯一性的常用方法。大多数数据库系统都支持自增主键。
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50),
email VARCHAR(100)
);
在Java中,你可以通过JDBC操作数据库来获取自增主键的值。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class AutoIncrementExample {
public static void main(String[] args) {
String url = “jdbc:mysql://localhost:3306/mydatabase”;
String user = “root”;
String password = “password”;

try (Connection conn = DriverManager.getConnection(url, user, password)) {
String sql = “INSERT INTO users (username, email) VALUES (?, ?)”;
try (PreparedStatement pstmt = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS)) {
pstmt.setString(1, “john_doe”);
pstmt.setString(2, “john@example.com”);
int affectedRows = pstmt.executeUpdate();

if (affectedRows == 0) {
throw new SQLException(“Creating user failed, no rows affected.”);
}

try (ResultSet generatedKeys = pstmt.getGeneratedKeys()) {
if (generatedKeys.next()) {
int id = generatedKeys.getInt(1);
System.out.println(“Generated ID: ” + id);
} else {
throw new SQLException(“Creating user failed, no ID obtained.”);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
高招三:分布式ID生成器
在分布式系统中,各个服务实例可能位于不同的服务器上,因此需要一个中央服务来生成全局唯一的ID。一种常见的方法是使用Twitter的Snowflake算法。
public class SnowflakeIdGenerator {
private long workerId;
private long datacenterId;
private long sequence = 0L;

private long twepoch = 1288834974657L;

private long workerIdBits = 5L;
private long datacenterIdBits = 5L;
private long maxWorkerId = -1L ^ (-1L << workerIdBits); private long maxDatacenterId = -1L ^ (-1L << datacenterIdBits); private long sequenceBits = 12L; private long workerIdShift = sequenceBits; private long datacenterIdShift = sequenceBits + workerIdBits; private long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits; private long sequenceMask = -1L ^ (-1L << sequenceBits); private long lastTimestamp = -1L; public SnowflakeIdGenerator(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; } private long tilNextMillis(long lastTimestamp) { long timestamp = timeGen(); while (timestamp <= lastTimestamp) { timestamp = timeGen(); } return timestamp; } private long timeGen() { return System.currentTimeMillis(); } } 高招四:使用Redis生成唯一ID Redis是一个高性能的键值存储系统,它可以用来生成唯一ID。利用Redis的原子操作,可以确保生成的ID的唯一性。 import redis.clients.jedis.Jedis; public class RedisIdGenerator { private Jedis jedis; public RedisIdGenerator(Jedis jedis) { this.jedis = jedis; } public String generateId(String key) { String id = jedis.incr(key).toString(); return id; } public static void main(String[] args) { Jedis jedis = new Jedis("localhost"); RedisIdGenerator generator = new RedisIdGenerator(jedis); String uniqueId = generator.generateId("unique_id_key"); System.out.println("Generated ID: " + uniqueId); } } 高招五:基于时间戳和随机数的组合 结合时间戳和随机数,可以生成一个相对唯一的ID。这种方法简单易行,但可能存在一定的冲突概率。 import java.util.concurrent.atomic.AtomicLong; public class TimeBasedIdGenerator { private static final AtomicLong lastTimestamp = new AtomicLong(-1L); private static final long sequence = 0L; public static String generateId() { long timestamp = System.currentTimeMillis(); if (timestamp < lastTimestamp.get()) { throw new RuntimeException("Clock moved backwards. Refusing to generate id."); } if (timestamp == lastTimestamp.get()) { sequence++; if (sequence >= 4096) {
timestamp = tilNextMillis(lastTimestamp.get());
}
} else {
sequence = 0L;
}

lastTimestamp.set(timestamp);
return String.format(“%016d%012d”, timestamp, sequence);
}

private static long tilNextMillis(long lastTimestamp) {
long timestamp = System.currentTimeMillis();
while (timestamp <= lastTimestamp) { timestamp = System.currentTimeMillis(); } return timestamp; } } 总结 以上五种方法都是Java中保证ID唯一性的有效手段。根据具体的应用场景和需求,可以选择最合适的方法来生成唯一ID。在实际应用中,还需要考虑性能、可扩展性和容错性等因素。