前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >分布式id生成算法SnowFlake

分布式id生成算法SnowFlake

作者头像
chenchenchen
发布2019-09-03 14:44:00
8750
发布2019-09-03 14:44:00
举报
文章被收录于专栏:chenchenchenchenchenchen

符号位说明:

第一位为不能为负的符号位:0

时间戳说明:

41位记录时间戳timeMillis,即当前系统时间 - 默认固定时间的值

工作机器ID说明:

10位记录工作机器id;即datacenterId (5位数据id) + workerId (5位机器id)

datacenterId 与 workerId的最大值十进制值是31(不能为负数)

原因:5位数的最大二进制表示: 0001 1111 —> 十进制:31

序列号说明:

12位自增序列号sequence

Sequence的最大十进制值是4095(不能为负数)

原因:12位数的最大二进制表示:1111 1111 1111 —> 十进制:4095

二进制说明:

按位或,按位与,异或计算例子:

位移说明:

计算所需默认常量

默认固定时间twepoch: 1288834974657(毫秒)(小于当前时间即可,不能出现负数)

时间戳偏移位数 timestampLeftShift:22(给5位机器id、5位数据id、12位序列号移除位置)

数据id偏移位数 datacenterIdShift:17(给5位数据id、12位序列号移除位置)

机器id偏移位数 workerIdShift:12(给12位序列号移除位置)

开始计算

一,需要输入的条件(以这4个数据为例):

  1. 当前时间 timwstamp:1563244877076(毫秒)
  2. 机器id workerId:6(本机ip)
  3. 数据id datacentId:20(当前进程Hashmap)
  4. 序列号sequence:0(自增序列号)

二,计算

计算公式

步骤:

1.首先计算时间戳;即:timeMillis = timestamp(当前时间) – twepoch(固定时间)

timeMillis : 1563244877076 – 1288834974657 = 274409902419

2.再先分别计算左位移结果

timeMillis << timestampLeftShift

转换: 274409902419 << 22

二进制: 0011111111100100000110101101000101010011 << 22

//位移前

0000 0000 0000 0000 0000 0000 0011 1111 1110 0100 0001 1010 1101 0001 0101 0011

//位移22位后的结果(标记:a)

0000 1111 1111 1001 0000 0110 1011 0100 0101 0100 1100 0000 0000 0000 0000 0000

datacenterId << datacenterIdShift

转换: 20 << 17

二进制:0001 0100 << 17

//位移前

0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0001 0100

//位移17位后的结果(标记:b)

0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0010 1000 0000 0000 0000 0000

workerId << workerIdShift

转换:6 << 12

二进制:0000 0110 << 12

//位移前

0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0110

//位移12位后的结果(标记:c)

0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0110 0000 0000 0000

3.最后计算按位或的结果

计算公式带入值:

274409902419 << 22 |

20 << 17 |

6 << 12 |

0

||

|| 简化

\ || /

a | b | c | 0

||

|| 二进制表示

\ || /

| 41位 | 5 | 5 | 12位

0|000 1111 1111 1001 0000 0110 1011 0100 0101 0100 11|00 000|0 0000| 0000 0000 0000 | //a

0|000 0000 0000 0000 0000 0000 0000 0000 0000 0000 00|10 100|0 0000| 0000 0000 0000 | //b

0|000 0000 0000 0000 0000 0000 0000 0000 0000 0000 00|00 000|0 0110| 0000 0000 0000 | //c

0|000 0000 0000 0000 0000 0000 0000 0000 0000 0000 00|00 000|0 0000| 0000 0000 0000 | //0

0|000 1111 1111 1001 0000 0110 1011 0100 0101 0100 11|10 100|0 0110| 0000 0000 0000 //结果

最终结果:

二进制:0000 1111 1111 1001 0000 0110 1011 0100 0101 0100 1110 1000 0110 0000 0000 0000

十进制:1150958551358267392

代码

import java.lang.management.ManagementFactory; import java.net.InetAddress; import java.net.NetworkInterface;

/** * <p> * 名称:IdWorker.java * </p> * <p> * 描述:分布式自增长ID * </p> * * <pre> * Twitter的 Snowflake JAVA实现方案 * </pre> * * 核心代码为其IdWorker这个类实现,其原理结构如下,我分别用一个0表示一位,用—分割开部分的作用: 1||0---0000000000 * 0000000000 0000000000 0000000000 0 --- 00000 ---00000 ---000000000000 * 在上面的字符串中,第一位为未使用(实际上也可作为long的符号位),接下来的41位为毫秒级时间, * 然后5位datacenter标识位,5位机器ID(并不算标识符,实际是为线程标识), * 然后12位该毫秒内的当前毫秒内的计数,加起来刚好64位,为一个Long型。 * 这样的好处是,整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞(由datacenter和机器ID作区分), * 并且效率较高,经测试,snowflake每秒能够产生26万ID左右,完全满足需要。 * <p> * 64位ID (42(毫秒)+5(机器ID)+5(业务编码)+12(重复累加)) * * @author system */ public class IdWorker { // 时间起始标记点,作为基准,一般取系统的最近时间(一旦确定不能变动) private final static long twepoch = 1288834974657L; // 机器标识位数 private final static long workerIdBits = 5L; // 数据中心标识位数 private final static long datacenterIdBits = 5L; // 机器ID最大值 private final static long maxWorkerId = -1L ^ (-1L << workerIdBits); // 数据中心ID最大值 private final static long maxDatacenterId = -1L ^ (-1L << datacenterIdBits); // 毫秒内自增位 private final static long sequenceBits = 12L; // 机器ID偏左移12位 private final static long workerIdShift = sequenceBits; // 数据中心ID左移17位 private final static long datacenterIdShift = sequenceBits + workerIdBits; // 时间毫秒左移22位 private final static long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;

private final static long sequenceMask = -1L ^ (-1L << sequenceBits); /* 上次生产id时间戳 */ private static long lastTimestamp = -1L; // 0,并发控制 private long sequence = 0L;

private final long workerId; // 数据标识id部分 private final long datacenterId;

public IdWorker() { this.datacenterId = getDatacenterId(maxDatacenterId); this.workerId = getMaxWorkerId(datacenterId, maxWorkerId); }

/** * @param workerId * 工作机器ID * @param datacenterId * 序列号 */ public IdWorker(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; }

/** * 获取下一个ID * * @return */ 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) { // 当前毫秒内,则+1 sequence = (sequence + 1) & sequenceMask; if (sequence == 0) { // 当前毫秒内计数满了,则等待下一秒 timestamp = tilNextMillis(lastTimestamp); } } else { sequence = 0L; } lastTimestamp = timestamp; System.out.println("timestamp:"+timestamp); System.out.println("twepoch:"+twepoch); System.out.println("workerId:"+workerId); System.out.println("datacenterId:"+datacenterId); System.out.println("sequence:"+sequence); // ID偏移组合生成最终的ID,并返回ID long nextId = ((timestamp - twepoch) << timestampLeftShift) | (datacenterId << datacenterIdShift) | (workerId << workerIdShift) | sequence;

return nextId; }

private long tilNextMillis(final long lastTimestamp) { long timestamp = this.timeGen(); while (timestamp <= lastTimestamp) { timestamp = this.timeGen(); } return timestamp; }

private long timeGen() { return System.currentTimeMillis(); }

/** * <p> * 获取 maxWorkerId * </p> */ protected static long getMaxWorkerId(long datacenterId, long maxWorkerId) { StringBuffer mpid = new StringBuffer(); mpid.append(datacenterId); String name = ManagementFactory.getRuntimeMXBean().getName(); if (!name.isEmpty()) { /* * GET jvmPid */ mpid.append(name.split("@")[0]); } /* * MAC + PID 的 hashcode 获取16个低位 */ return (mpid.toString().hashCode() & 0xffff) % (maxWorkerId + 1); }

/** * <p> * 数据标识id部分 * </p> */ protected static long getDatacenterId(long maxDatacenterId) { long id = 0L; try { InetAddress ip = InetAddress.getLocalHost(); NetworkInterface network = NetworkInterface.getByInetAddress(ip); if (network == null) { id = 1L; } else { byte[] mac = network.getHardwareAddress(); id = ((0x000000FF & (long) mac[mac.length - 1]) | (0x0000FF00 & (((long) mac[mac.length - 2]) << 8))) >> 6; id = id % (maxDatacenterId + 1); } } catch (Exception e) { System.out.println(" getDatacenterId: " + e.getMessage()); } return id; }

public static void main(String[] args) {

IdWorker id = new IdWorker(13, 30); System.out.println(id.nextId());

}

}

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019年07月17日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档