what is SnowflakeId
随着服务化的演进,服务越来越多,数据库越分越细,有时候一个业务也会用到多个数据库。这时,使用传统的主键自增或者UUID(无序,长度过长)方式就会产生id重复,不能满足使用场景。分布式系统中为了保证id唯一,就需要全局的唯一id生成策略。
雪花算法优点:
生成的ID不重复
生成性能高(每向数据库插入一条数据不用进行重新排列)
基于时间戳,可以基本保证有序递增
雪花算法存在的问题:
时间回拨问题:由于机器的时间是动态的调整的,有可能会出现时间跑到之前几毫秒,如果这个时候获取到了这种时间,则会出现数据重复
机器id分配及回收问题:目前机器id需要每台机器不一样,这样的方式分配需要有方案进行处理,同时也要考虑,如果改机器宕机了,对应的workerId分配后的回收问题
机器id上限:机器id是固定的bit,那么也就是对应的机器个数是有上限的,在有些业务场景下,需要所有机器共享同一个业务空间,那么10bit表示的1024台机器是不够的。
why is SnowflakeId
snowflake生成的ID整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞(由datacenter和workerId作区分),并且效率较高。据说snowflake每秒能够产生26万个ID。
how to do
snowflake的结构如下(每部分用-分开):
0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000
第一位为符号位不使用,接下来的41位为毫秒级时间(41位的长度可以使用69年),
然后是5位datacenterId和5位workerId(10位的长度最多支持部署1024个节点) ,(5+5,0+10可以调整)
最后12位是毫秒内的计数(12位的计数顺序号支持每个节点每毫秒产生4096个ID序号)
一共加起来刚好64位,为一个Long型。
java中long类型占8字节,1字节=8位(1byte=8bit)也就是64位,每一位都有0和1两种状态,64位也就可以表示264个状态,也就是264个数,而long类型是有符号的(分正负),负数用-263至-1表示,正数用0至263-1表示,加起来正是2^64个数
long MAX_VALUE = -1L ^ (-1L << 63)= 9223372036854775807L(最大长度19位)
/**
* Snowflake 基于雪花算法的ID生成器
*/
public class SnowflakeIdWorker {
//定义起始时间:一般地,选用系统上线的时间2021-01-01 00:00:00
private final long startTime = 1609430400000L;
//序列号位数
private final long sequenceBits = 12L;
//机器ID位数
private final long workerIdBits = 5L;
//数据中心ID位数
private final long datacenterIdBits = 5L;
//序列号最大值, 4095
private final long sequenceMask = -1L ^ (-1L << sequenceBits);
//机器ID最大值, 31
private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
//数据中心ID最大值, 31
private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
//机器ID左移位数, 12
private final long workerIdShift = sequenceBits;
//数据中心ID左移位数, 12+5
private final long datacenterIdShift = sequenceBits + workerIdBits;
//时间戳左移位数, 12+5+5
private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
private long workerId;
private long datacenterId;
//相同毫秒内的序列号, Value Range: [0,4095]
private long sequence = 0L;
//上一次生成id使用的时间戳
private long lastTimestamp = -1L;
public SnowflakeIdWorker(long workerId, long datacenterId) {
if (workerId <= 31L && workerId >= 0L) {
if (datacenterId <= 31L && datacenterId >= 0L) {
this.workerId = workerId;
this.datacenterId = datacenterId;
} else {
throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
}
} else {
throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
}
}
public SnowflakeIdWorker() {
}
/**
* 获取ID
*
* @return
*/
public synchronized long nextId() {
long timestamp = this.timeGen();
//当前时间小于上一次生成ID的时间戳,系统时钟被回
if (timestamp < this.lastTimestamp) {
throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", this.lastTimestamp - timestamp));
} else {
//当前时间等于上一次生成ID的时间戳,则通过序列号来区分
if (this.lastTimestamp == timestamp) {
//通过序列号掩码实现只取 (sequence+1) 的低12位结果,其余位全部清零
this.sequence = this.sequence + 1L & sequenceMask;
//该时间戳下的序列号已经溢出
if (this.sequence == 0L) {
//阻塞等待下一个毫秒,并获取新的时间戳
timestamp = this.tilNextMillis(this.lastTimestamp);
}
} else {
//当前时间大于上一次生成ID的时间戳,重置序列号
this.sequence = 0L;
}
//更新上次时间戳信息
this.lastTimestamp = timestamp;
//生成此次ID
return timestamp - startTime << timestampLeftShift | this.datacenterId << datacenterIdShift | this.workerId << workerIdShift | this.sequence;
}
}
/**
* 阻塞等待,直到获取新的时间戳(下一个毫秒)
*
* @param lastTimestamp
* @return
*/
protected long tilNextMillis(long lastTimestamp) {
long timestamp;
for (timestamp = this.timeGen(); timestamp <= lastTimestamp; timestamp = this.timeGen()) {
}
return timestamp;
}
protected long timeGen() {
return System.currentTimeMillis();
}
public long getWorkerId() {
return this.workerId;
}
public void setWorkerId(long workerId) {
this.workerId = workerId;
}
public long getDatacenterId() {
return this.datacenterId;
}
public void setDatacenterId(long datacenterId) {
this.datacenterId = datacenterId;
}
public static void main(String[] args) {
SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0L, 0L);
for (int i = 0; i < 10000000; ++i) {
long id = idWorker.nextId();
System.out.println(Long.toBinaryString(id));
System.out.println(id);
}
}
}
note
- 计算X位Bit能表示的最大值
计算X位Bit能表示的最大值,最简单的是 Math.pow(2,X)-1,不过还可以通过位运算来提高速度,即 -1^(-1<<X)。
在计算机的二进制下 -1 使用全1进行表示
这里以X等于3为例作图解说明
- 41位时间戳可以使用多久