package com.ruoyi.web.tool; /** * id生成器 */ public class IDUtil { /** * 存储时间戳 */ private static long timestamp = System.currentTimeMillis(); /** * 自增长值 */ private static int self = 0; /** * 最大自增长值 */ private static int max_self = 9999; /** * 设备号 */ private static int device = 0; /** * 时针回拨增长值 */ private static int hour_hand_variable = 0; /** * 时针回拨最大增长值 */ private static int max_hour_hand_variable = 999; /** * 时间戳id * @return */ public static long timestamp_id(){ return timestamp; } /** * 生成唯一ID * @return */ public static long sole_id(){ return sole_id(null); } /** * 唯一ID生成 * @param workId 工作ID * @return */ public synchronized static long sole_id(Integer workId){ if(null != workId){ device = workId; } long timeMillis = System.currentTimeMillis(); /** * 时间戳相同 * 自增长值使用完后,休眠等待时间戳更新 */ if(timeMillis == timestamp && self > max_self){ try { Thread.sleep(1); self = 0; return sole_id(workId); } catch (InterruptedException e) { throw new RuntimeException(e); } } //处理时针回拨的情况 if(timeMillis < timestamp) { if (hour_hand_variable >= max_hour_hand_variable) { hour_hand_variable = 0; } else { hour_hand_variable++; } } //处理 if(timeMillis > timestamp){ timestamp = timeMillis; self = 0; } return splice(); } /** * 拼接最终的id * @return */ private static long splice(){ //格式化自增长数据格式,前位补0 String format = String.format("%04d", self); Long id = Long.valueOf(timestamp + "" + hour_hand_variable + "" + device + format); self++; return id; } }