雪花算法
雪花算法(SnowFlake)是由Twitter开源的分布式ID生成算法。
简介
基于这个算法可以生成ID,来作为分布式环境下全局唯一ID。
生成的ID是一个long型(64bit),以下是雪花算法生成的ID的二进制形式示图。
描述:
1.符号位,默认为0表示正数
2.时间戳,表示具体的某一毫秒
3.机器ID,表示当前运行该算法的机器ID。10bit最多支持1024(2^10)个机器ID
4.序列号,当前同一机器统一毫秒所产生的ID序列号。同一毫秒内最多能生成4095(2^12-1)个ID
具体应用
某一个服务需要使用分布式全局唯一ID,则可以发送请求给部署了雪花算法,然后获取到由雪花算法生成的ID。
package com.charwayh;
/**
* @author charwayH
* 官方推出,Scala编程语言来实现的
* 以下是用Java语言实现的雪花算法
*/
public class IdWorker{
/**
* 下面两个每个5位,加起来就是10位的工作机器id
* workerId 机器id 2进制5位
* datacenterId 机房id 2进制5位
*
* sequence 序列号 2进制12位
*/
private long workerId;
private long datacenterId;
private long sequence;
public IdWorker(long workerId, long datacenterId, long sequence){
// sanity check for workerId
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));
}
System.out.printf("worker starting. timestamp left shift %d, datacenter id bits %d, worker id bits %d, sequence bits %d, workerid %d",
timestampLeftShift, datacenterIdBits, workerIdBits, sequenceBits, workerId);
this.workerId = workerId;
this.datacenterId = datacenterId;
this.sequence = sequence;
}
/**
* twepoch 初始时间戳
*/
private long twepoch = 1288834974657L;
/**
* workerIdBits 机器id位数
* datacenterIdBits 机房id位数
* 长度为5位
*
* maxWorkerId 机器id最大值
* maxDatacenterId 机房id最大值
*/
private long workerIdBits = 5L;
private long datacenterIdBits = 5L;
private long maxWorkerId = -1L ^ (-1L << workerIdBits);
private long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
/**
* sequenceBits 序列号id长度
* sequenceMask 序列号最大值
*/
private long sequenceBits = 12L;
private long sequenceMask = -1L ^ (-1L << sequenceBits);
/**
* workerIdShift 工作id需要左移的位数,12位
* datacenterIdShift 数据id需要左移位数 12+5=17位
* timestampLeftShift 时间戳需要左移位数 12+5+5=22位
*/
private long workerIdShift = sequenceBits;
private long datacenterIdShift = sequenceBits + workerIdBits;
private long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
/**
* lastTimestamp 上次时间戳,初始值为负数
*/
private long lastTimestamp = -1L;
public long getWorkerId(){
return workerId;
}
public long getDatacenterId(){
return datacenterId;
}
public long getTimestamp(){
return System.currentTimeMillis();
}
/**
* 下一个ID生成算法
* @return 返回ID
*/
public synchronized long nextId() {
long timestamp = timeGen();
// 获取当前时间戳如果小于上次时间戳,则表示时间戳获取出现异常
if (timestamp < lastTimestamp) {
System.err.printf("clock is moving backwards. Rejecting requests until %d.", lastTimestamp);
throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds",
lastTimestamp - timestamp));
}
// 获取当前时间戳如果等于上次时间戳
// 说明:还处在同一毫秒内,则在序列号加1;否则序列号赋值为0,从0开始。
// 0 - 4095
if (lastTimestamp == timestamp) {
sequence = (sequence + 1) & sequenceMask;
if (sequence == 0) {
timestamp = tilNextMillis(lastTimestamp);
}
} else {
sequence = 0;
}
// 将上次时间戳值刷新
lastTimestamp = timestamp;
/**
* 返回结果:
* (timestamp - twepoch) << timestampLeftShift) 表示将时间戳减去初始时间戳,再左移相应位数
* (datacenterId << datacenterIdShift) 表示将数据id左移相应位数
* (workerId << workerIdShift) 表示将工作id左移相应位数
* | 是按位或运算符,例如:x | y,只有当x,y都为0的时候结果才为0,其它情况结果都为1。
* 因为个部分只有相应位上的值有意义,其它位上都是0,所以将各部分的值进行 | 运算就能得到最终拼接好的id
*/
return ((timestamp - twepoch) << timestampLeftShift) |
(datacenterId << datacenterIdShift) |
(workerId << workerIdShift) |
sequence;
}
/**
* @param lastTimestamp 上次的时间戳
* 获取时间戳,并与上次时间戳比较
*/
private long tilNextMillis(long lastTimestamp) {
long timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
}
return timestamp;
}
/**
* 获取系统时间戳
*/
private long timeGen(){
return System.currentTimeMillis();
}
/**
* 测试示例
* @param args
*/
public static void main(String[] args) {
IdWorker worker = new IdWorker(21,10,0);
for (int i = 0; i < 100; i++) {
System.out.println(worker.nextId());
}
}
}