項目中需要一個分布式的Id生成器,twitter的Snowflake中這個既簡單又高效,網上找的Java版本
package com.cqfc.id; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * tweeter的snowflake 移植到Java: * (a) id構成: 42位的時間前綴 + 10位的節點標識 + 12位的sequence避免並發的數字(12位不夠用時強制得到新的時間前綴) * 注意這里進行了小改動: snowkflake是5位的datacenter加5位的機器id; 這里變成使用10位的機器id * (b) 對系統時間的依賴性非常強,需關閉ntp的時間同步功能。當檢測到ntp時間調整后,將會拒絕分配id */ public class IdWorker { private final static Logger logger = LoggerFactory.getLogger(IdWorker.class); private final long workerId; private final long epoch = 1403854494756L; // 時間起始標記點,作為基准,一般取系統的最近時間 private final long workerIdBits = 10L; // 機器標識位數 private final long maxWorkerId = -1L ^ -1L << this.workerIdBits;// 機器ID最大值: 1023 private long sequence = 0L; // 0,並發控制 private final long sequenceBits = 12L; //毫秒內自增位 private final long workerIdShift = this.sequenceBits; // 12 private final long timestampLeftShift = this.sequenceBits + this.workerIdBits;// 22 private final long sequenceMask = -1L ^ -1L << this.sequenceBits; // 4095,111111111111,12位 private long lastTimestamp = -1L; private IdWorker(long workerId) { 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() throws Exception { long timestamp = this.timeGen(); if (this.lastTimestamp == timestamp) { // 如果上一個timestamp與新產生的相等,則sequence加一(0-4095循環); 對新的timestamp,sequence從0開始 this.sequence = this.sequence + 1 & this.sequenceMask; if (this.sequence == 0) { timestamp = this.tilNextMillis(this.lastTimestamp);// 重新生成timestamp } } else { this.sequence = 0; } if (timestamp < this.lastTimestamp) { logger.error(String.format("clock moved backwards.Refusing to generate id for %d milliseconds", (this.lastTimestamp - timestamp))); throw new Exception(String.format("clock moved backwards.Refusing to generate id for %d milliseconds", (this.lastTimestamp - timestamp))); } this.lastTimestamp = timestamp; return timestamp - this.epoch << this.timestampLeftShift | this.workerId << this.workerIdShift | this.sequence; } private static IdWorker flowIdWorker = new IdWorker(1); public static IdWorker getFlowIdWorkerInstance() { return flowIdWorker; } /** * 等待下一個毫秒的到來, 保證返回的毫秒數在參數lastTimestamp之后 */ private long tilNextMillis(long lastTimestamp) { long timestamp = this.timeGen(); while (timestamp <= lastTimestamp) { timestamp = this.timeGen(); } return timestamp; } /** * 獲得系統當前毫秒數 */ private static long timeGen() { return System.currentTimeMillis(); } public static void main(String[] args) throws Exception { System.out.println(timeGen()); IdWorker idWorker = IdWorker.getFlowIdWorkerInstance(); // System.out.println(Long.toBinaryString(idWorker.nextId())); System.out.println(idWorker.nextId()); System.out.println(idWorker.nextId()); } }