1. 程式人生 > >雪花演算法生成長整型ID工具類SnowflakeUtil

雪花演算法生成長整型ID工具類SnowflakeUtil

JS語言不支援15位以上的長整型,該工具使用與否要有取捨。

public class SnowflakeUtil {

	/** 開始時間截 (2015-01-01) */
	private final static long TWEPOCH = 1420041600000L;
	/** 工作機器ID(0~31) */
	private final static long WORKER_ID = getWorkerId();
	/** 資料中心ID(0~31) */
	private final static long DATA_CENTER_ID = getDataCenterId();
	/** 機器id所佔的位數 */
	private final static long WORKER_ID_BITS = 8L;
	/** 資料標識id所佔的位數 */
	private final static long DATA_CENTER_ID_BITS = 2L;
	/** 支援的最大機器id,結果是31 (這個移位演算法可以很快的計算出幾位二進位制數所能表示的最大十進位制數) */
	private final static long MAX_WORKER_ID = -1L ^ (-1L << WORKER_ID_BITS);
	/** 支援的最大資料標識id,結果是31 */
	private final static long MAX_DATA_CENTER_ID = -1L ^ (-1L << DATA_CENTER_ID_BITS);
	/** 序列在id中佔的位數 */
	private final static long SEQUENCE_BITS = 12L;
	/** 機器ID向左移12位 */
	private final static long WORKER_ID_SHIFT = SEQUENCE_BITS;
	/** 資料標識id向左移17位(12+5) */
	private final static long DATA_CENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS;
	/** 時間截向左移22位(5+5+12) */
	private final static long TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATA_CENTER_ID_BITS;
	/** 生成序列的掩碼,這裡為4095 (0b111111111111=0xfff=4095) */
	private final static long SEQUENCE_MASK = -1L ^ (-1L << SEQUENCE_BITS);
	/** 毫秒內序列(0~4095) */
	private static long sequence = 0L;
	/** 上次生成ID的時間截 */
	private static long lastTimestamp = -1L;

	/**
	 * 獲得下一個ID (該方法是執行緒安全的)
	 * 
	 * @return SnowflakeId
	 */
	public static synchronized long nextId() {
		if (WORKER_ID > MAX_WORKER_ID || WORKER_ID < 0) {
			throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", MAX_WORKER_ID));
		}
		if (DATA_CENTER_ID > MAX_DATA_CENTER_ID || DATA_CENTER_ID < 0) {
			throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", MAX_DATA_CENTER_ID));
		}
		long timestamp = System.currentTimeMillis();
		// 如果當前時間小於上一次ID生成的時間戳,說明系統時鐘回退過這個時候應當丟擲異常
		if (timestamp < lastTimestamp) {
			throw new RuntimeException(String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
		}
		// 如果是同一時間生成的,則進行毫秒內序列
		if (lastTimestamp == timestamp) {
			sequence = (sequence + 1) & SEQUENCE_MASK;
			// 毫秒內序列溢位
			if (sequence == 0) {
				// 阻塞到下一個毫秒,獲得新的時間戳
				timestamp = tilNextMillis(lastTimestamp);
			}
		}
		// 時間戳改變,毫秒內序列重置
		else {
			sequence = 0L;
		}
		// 上次生成ID的時間截
		lastTimestamp = timestamp;
		// 移位並通過或運算拼到一起組成64位的ID
		return ((timestamp - TWEPOCH) << TIMESTAMP_LEFT_SHIFT) //
				| (DATA_CENTER_ID << DATA_CENTER_ID_SHIFT) //
				| (WORKER_ID << WORKER_ID_SHIFT) //
				| sequence;
	}

	/**
	 * 阻塞到下一個毫秒,直到獲得新的時間戳
	 * 
	 * @param lastTimestamp
	 *            上次生成ID的時間截
	 * @return 當前時間戳
	 */
	private static long tilNextMillis(long lastTimestamp) {
		long timestamp = System.currentTimeMillis();
		while (timestamp <= lastTimestamp) {
			timestamp = System.currentTimeMillis();
		}
		return timestamp;
	}

	public static Long getWorkerId() {
		return Long.parseLong(StringUtils.substringAfterLast(IpUtil.getLocalHostLANAddress().getHostAddress(), "."));
	}

	public static Long getDataCenterId() {
		return (long) (Math.random() * 3 + 1);
	}

}