在工作中会遇到需要生成唯一单号的需求,最近我在工作中也碰到了,整理了三种常用的生成唯一订单的方式:
- 时间戳+随机数
String orderId = System.currentTimeMillis() + "" + (int)(Math.random()*9000+1000);
- UUID
String orderId = UUID.randomUUID().toString().replaceAll("-", "");
- 雪花算法
雪花算法是一种分布式唯一ID生成器,可以保证集群内全局唯一,同时也具备趋势递增和高可用等特性。
public class SnowflakeIdWorker {
private final long workerId;
private final static long twepoch = 1288834974657L;
private long sequence = 0L;
private final static long workerIdBits = 4L;
public final static long maxWorkerId = -1L ^ -1L << workerIdBits;
private final static long sequenceBits = 10L;
private final static long workerIdShift = sequenceBits;
private final static long timestampLeftShift = sequenceBits + workerIdBits;
public final static long sequenceMask = -1L ^ -1L << sequenceBits;
private long lastTimestamp = -1L;
public SnowflakeIdWorker(final long workerId) {
super();
if (workerId > this.maxWorkerId || workerId < 0) {
throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", this.maxWorkerId));
}
this.workerId = workerId;
}
public synchronized long nextId() {
long timestamp = this.timeGen();
if (this.lastTimestamp == timestamp) {
this.sequence = this.sequence + 1 & this.sequenceMask;
if (this.sequence == 0L) {
timestamp = this.tilNextMillis(this.lastTimestamp);
}
} else {
this.sequence = 0L;
}
if (timestamp < this.lastTimestamp) {
throw new RuntimeException(String.format("Clock moved backwards. Detected a clock reset after %d milliseconds", (this.lastTimestamp - timestamp)));
}
this.lastTimestamp = timestamp;
return timestamp - twepoch << timestampLeftShift | this.workerId << this.workerIdShift | this.sequence;
}
private long tilNextMillis(final long lastTimestamp) {
long timestamp = this.timeGen();
while (timestamp <= lastTimestamp) {
timestamp = this.timeGen();
}
return timestamp;
}
private long timeGen() {
return System.currentTimeMillis();
}
}
使用方式:
SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0);
String orderId = String.valueOf(idWorker.nextId());
当然,生成唯一订单号的方式并不局限于这三种,如果有更好的方式,欢迎留言讨论。
关注公众号,加入技术群,一起探讨前沿技术: