雪花算法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 | import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.management.ManagementFactory; import java.net.InetAddress; import java.net.NetworkInterface; import java.util.Date; import java.util.concurrent.ThreadLocalRandom; /** * @author NiaoGe * <p> * 雪花算法生成唯一 id,参考开源项目: * https://gitee.com/yu120/sequence * https://apidoc.gitee.com/loolly/hutool/cn/hutool/core/util/IdUtil.html * </p> */ public class IdGenerator { private static final Logger logger = LoggerFactory.getLogger(IdGenerator. class ); //工作机器 id private long workerId; //数据中心 id private long datacenterId; //序列号 private long sequence = 0L; //基准时间,一般取系统的最近时间(一旦确定不能变动) private long twepoch; private long workerIdBits; private long datacenterIdBits; private long maxWorkerId; private long maxDatacenterId; //毫秒内自增位数 private long sequenceBits; //位与运算保证毫秒内 Id 范围 private long sequenceMask; //工作机器 id 需要左移的位数 private long workerIdShift; //数据中心 id 需要左移位数 private long datacenterIdShift; //时间戳需要左移位数 private long timestampLeftShift; //上次生成 id 的时间戳,初始值为负数 private long lastTimestamp = -1L; //true 表示毫秒内初始序列采用随机值 private boolean randomSequence; //随机初始序列计数器 private long count = 0L; //允许时钟回拨的毫秒数 private long timeOffset; private final ThreadLocalRandom tlr = ThreadLocalRandom.current(); /** * 无参构造器,自动生成 workerId/datacenterId */ public IdGenerator() { this ( false , 10 , null , 5L, 5L, 12L); } /** * 有参构造器,调用者自行保证数据中心 ID+机器 ID 的唯一性 * 标准 snowflake 实现 * * @param workerId 工作机器 ID * @param datacenterId 数据中心 ID */ public IdGenerator( long workerId, long datacenterId) { this (workerId, datacenterId, false , 10 , null , 5L, 5L, 12L); } /** * @param randomSequence true 表示每毫秒内起始序号使用随机值 * @param timeOffset 允许时间回拨的毫秒数 * @param epochDate 基准时间 * @param workerIdBits workerId 位数 * @param datacenterIdBits datacenterId 位数 * @param sequenceBits sequence 位数 */ public IdGenerator( boolean randomSequence, long timeOffset, Date epochDate, long workerIdBits, long datacenterIdBits, long sequenceBits) { if ( null != epochDate) { this .twepoch = epochDate.getTime(); } else { // 2012/12/12 23:59:59 GMT this .twepoch = 1355327999000L; } this .workerIdBits = workerIdBits; this .datacenterIdBits = datacenterIdBits; this .maxWorkerId = -1L ^ (-1L << workerIdBits); this .maxDatacenterId = -1L ^ (-1L << datacenterIdBits); this .sequenceBits = sequenceBits; this .sequenceMask = -1L ^ (-1L << sequenceBits); this .workerIdShift = sequenceBits; this .datacenterIdShift = sequenceBits + workerIdBits; this .timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits; this .datacenterId = getDatacenterId(maxDatacenterId); this .workerId = getMaxWorkerId(datacenterId, maxWorkerId); this .randomSequence = randomSequence; this .timeOffset = timeOffset; String initialInfo = String.format( "worker starting. timestamp left shift %d, datacenter id bits %d, worker id bits %d, sequence bits %d, datacenterid %d, workerid %d" , timestampLeftShift, datacenterIdBits, workerIdBits, sequenceBits, datacenterId, workerId); logger.info(initialInfo); } /** * 自定义 workerId+datacenterId+其它初始配置 * 调整 workerId、datacenterId、sequence 位数定制雪花算法,控制生成的 Id 的位数 * * @param workerId 工作机器 ID * @param datacenterId 数据中心 ID * @param randomSequence true 表示每毫秒内起始序号使用随机值 * @param timeOffset 允许时间回拨的毫秒数 * @param epochDate 基准时间 * @param workerIdBits workerId 位数 * @param datacenterIdBits datacenterId 位数 * @param sequenceBits sequence 位数 */ public IdGenerator( long workerId, long datacenterId, boolean randomSequence, long timeOffset, Date epochDate, long workerIdBits, long datacenterIdBits, long sequenceBits) { this .workerIdBits = workerIdBits; this .datacenterIdBits = datacenterIdBits; this .maxWorkerId = -1L ^ (-1L << workerIdBits); this .maxDatacenterId = -1L ^ (-1L << datacenterIdBits); if (workerId > maxWorkerId || workerId < 0 ) { throw new IllegalArgumentException(String.format( "worker Id can't be greater than %d or less than 0\r\n" , maxWorkerId)); } if (datacenterId > maxDatacenterId || datacenterId < 0 ) { throw new IllegalArgumentException(String.format( "datacenter Id can't be greater than %d or less than 0\r\n" , maxDatacenterId)); } if ( null != epochDate) { this .twepoch = epochDate.getTime(); } else { // 2012/12/12 23:59:59 GMT this .twepoch = 1355327999000L; } this .sequenceBits = sequenceBits; this .sequenceMask = -1L ^ (-1L << sequenceBits); this .workerIdShift = sequenceBits; this .datacenterIdShift = sequenceBits + workerIdBits; this .timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits; this .workerId = workerId; this .datacenterId = datacenterId; this .timeOffset = timeOffset; this .randomSequence = randomSequence; String initialInfo = String.format( "worker starting. timestamp left shift %d, datacenter id bits %d, worker id bits %d, sequence bits %d, datacenterid %d, workerid %d" , timestampLeftShift, datacenterIdBits, workerIdBits, sequenceBits, datacenterId, workerId); logger.info(initialInfo); } private 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(); if ( null != mac) { id = (( 0x000000FF & ( long ) mac[mac.length - 1 ]) | ( 0x0000FF00 & ((( long ) mac[mac.length - 2 ]) << 8 ))) >> 6 ; id = id % (maxDatacenterId + 1 ); } } } catch (Exception e) { throw new RuntimeException( "GetDatacenterId Exception" , e); } return id; } private static long getMaxWorkerId( long datacenterId, long maxWorkerId) { StringBuilder macIpPid = new StringBuilder(); macIpPid.append(datacenterId); try { String name = ManagementFactory.getRuntimeMXBean().getName(); if (name != null && !name.isEmpty()) { //GET jvmPid macIpPid.append(name.split( "@" )[ 0 ]); } //GET hostIpAddress String hostIp = InetAddress.getLocalHost().getHostAddress(); String ipStr = hostIp.replaceAll( "\\." , "" ); macIpPid.append(ipStr); } catch (Exception e) { throw new RuntimeException( "GetMaxWorkerId Exception" , e); } //MAC + PID + IP 的 hashcode 取低 16 位 return (macIpPid.toString().hashCode() & 0xffff ) % (maxWorkerId + 1 ); } public synchronized long nextId() { long currentTimestamp = timeGen(); //获取当前时间戳如果小于上次时间戳,则表示时间戳获取出现异常 if (currentTimestamp < lastTimestamp) { // 校验时间偏移回拨量 long offset = lastTimestamp - currentTimestamp; if (offset > timeOffset) { throw new RuntimeException( "Clock moved backwards, refusing to generate id for [" + offset + "ms]" ); } try { // 时间回退 timeOffset 毫秒内,则允许等待 2 倍的偏移量后重新获取,解决小范围的时间回拨问题 this .wait(offset << 1 ); } catch (Exception e) { throw new RuntimeException(e); } currentTimestamp = timeGen(); if (currentTimestamp < lastTimestamp) { throw new RuntimeException( "Clock moved backwards, refusing to generate id for [" + offset + "ms]" ); } } //如果获取的当前时间戳等于上次时间戳(即同一毫秒内),则序列号自增 if (lastTimestamp == currentTimestamp) { // randomSequence 为 true 表示随机生成允许范围内的起始序列,否则毫秒内起始值从 0L 开始自增 long tempSequence = sequence + 1 ; if (randomSequence) { sequence = tempSequence & sequenceMask; count = (count + 1 ) & sequenceMask; if (count == 0 ) { currentTimestamp = this .tillNextMillis(lastTimestamp); } } else { sequence = tempSequence & sequenceMask; if (sequence == 0 ) { currentTimestamp = this .tillNextMillis(lastTimestamp); } } } else { sequence = randomSequence ? tlr.nextLong(sequenceMask + 1 ) : 0L; count = 0L; } lastTimestamp = currentTimestamp; return ((currentTimestamp - twepoch) << timestampLeftShift) | (datacenterId << datacenterIdShift) | (workerId << workerIdShift) | sequence; } private long tillNextMillis( 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) { // for (int i = 0; i < 10; i++) { // IdGenerator idGenerator = new IdGenerator(); // new Thread(() -> { // for (int j = 0; j < 100; j++) { // System.out.println(idGenerator.nextId()); // } // }).start(); // } // IdGenerator idGenerator = new IdGenerator(1, 1); // for (int j = 0; j < 2000; j++) { // System.out.println(System.currentTimeMillis() + " " + idGenerator.nextId()); // } // IdGenerator idGenerator = new IdGenerator(true, 10, null, 3L, 2L, 7L); // for (int j = 0; j < 2000; j++) { // System.out.println(System.currentTimeMillis() + " " + idGenerator.nextId()); // } IdGenerator shortIdGenerator = new IdGenerator( 7 , 3 , true , 10 , null , 3 , 2 , 7 ); for ( int j = 0 ; j < 1000 ; j++) { System.out.println(System.currentTimeMillis() + " " + shortIdGenerator.nextId()); } } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2021-05-10 Synchronized的原理解读