以下是各大厂常用的数据库ID生成策略及相应的代码示例:
1. 自增ID(Auto Increment)
适用于单机数据库,如MySQL、PostgreSQL。
- 应用场景:主要用于单机数据库,如MySQL、PostgreSQL。
- 优点:简单易用,性能较好。
- 缺点:在分布式环境下难以保证唯一性和顺序性,需要额外处理。
MySQL示例:
CREATE TABLE example (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL
);
2. UUID(Universally Unique Identifier)
适用于需要全局唯一标识的场景。
- 应用场景:适用于需要全局唯一标识的场景。
- 优点:可以保证全局唯一性,适合分布式系统。
- 缺点:长度较长,占用存储空间较大,索引性能较差。
Java示例:
import java.util.UUID;
public class UUIDExample {
public static void main(String[] args) {
UUID uniqueID = UUID.randomUUID();
System.out.println(uniqueID);
}
}
3. 雪花算法(Snowflake Algorithm)
适用于高并发的分布式系统,Twitter开源的分布式ID生成算法
- 应用场景:Twitter开源的分布式ID生成算法,适用于高并发场景。
- 优点:生成的ID有序且唯一,适合分布式环境,性能好。
- 缺点:需要部署额外的ID生成服务。
Java示例:
public class SnowflakeIdGenerator {
private final long epoch = 1288834974657L;
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 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 - epoch) << 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();
}
}
4. 数据库分配ID(Database Assigned IDs)
利用数据库的序列号生成功能,如Oracle的Sequence。
- 应用场景:利用数据库的序列号生成功能,如Oracle的Sequence。
- 优点:数据库自身保证唯一性和有序性。
- 缺点:可能成为系统瓶颈,不适用于大规模分布式系统。
Oracle示例:
CREATE SEQUENCE example_seq START WITH 1 INCREMENT BY 1;
CREATE TABLE example (
id NUMBER PRIMARY KEY,
name VARCHAR2(255) NOT NULL
);
INSERT INTO example (id, name) VALUES (example_seq.NEXTVAL, 'example_name');
5. Redis生成ID
利用Redis的原子自增操作来生成唯一ID。
- 应用场景:利用Redis的原子自增操作来生成唯一ID。
- 优点:高性能,适合高并发环境。
- 缺点:需要维护Redis集群,存在单点故障风险。
Java示例(使用Jedis库):
import redis.clients.jedis.Jedis;
public class RedisIdGenerator {
private Jedis jedis;
private String key;
public RedisIdGenerator(String host, int port, String key) {
this.jedis = new Jedis(host, port);
this.key = key;
}
public long nextId() {
return jedis.incr(key);
}
public static void main(String[] args) {
RedisIdGenerator generator = new RedisIdGenerator("localhost", 6379, "unique_id");
System.out.println(generator.nextId());
}
}
6. Leaf(美团的分布式ID生成服务)
美团开源的分布式ID生成服务。
- 应用场景:美团开源的分布式ID生成服务。
- 优点:适合大规模分布式系统,生成的ID有序且唯一。
- 缺点:复杂性较高,需要部署和维护Leaf服务。
Leaf使用示例:
Leaf服务需要先进行配置和部署,以下是基本的使用方式:
import com.sankuai.inf.leaf.common.Result;
import com.sankuai.inf.leaf.snowflake.IDGen;
public class LeafIdGenerator {
private IDGen idGen;
public LeafIdGenerator(IDGen idGen) {
this.idGen = idGen;
}
public long nextId() {
Result result = idGen.get("");
if (result.getStatus() == Status.SUCCESS) {
return result.getId();
} else {
throw new RuntimeException("Failed to generate ID");
}
}
}