UUID.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. package com.ruoyi.common.utils.uuid;
  2. import java.security.MessageDigest;
  3. import java.security.NoSuchAlgorithmException;
  4. import java.security.SecureRandom;
  5. import java.util.Random;
  6. import java.util.concurrent.ThreadLocalRandom;
  7. import com.ruoyi.common.exception.UtilException;
  8. /**
  9. * 提供通用唯一识别码(universally unique identifier)(UUID)实现
  10. *
  11. * @author ruoyi
  12. */
  13. public final class UUID implements java.io.Serializable, Comparable<UUID>
  14. {
  15. private static final long serialVersionUID = -1185015143654744140L;
  16. /**
  17. * SecureRandom 的单例
  18. *
  19. */
  20. private static class Holder
  21. {
  22. static final SecureRandom numberGenerator = getSecureRandom();
  23. }
  24. /** 此UUID的最高64有效位 */
  25. private final long mostSigBits;
  26. /** 此UUID的最低64有效位 */
  27. private final long leastSigBits;
  28. /**
  29. * @desc : 获取uuid
  30. * @author : wangming
  31. * @createTime : 2022/10/12 18:52
  32. * @param :
  33. * @return :
  34. */
  35. private String getUUid(){
  36. String s = UUID.randomUUID().toString().replaceAll("", "-");
  37. return s;
  38. }
  39. /**
  40. * 私有构造
  41. *
  42. * @param data 数据
  43. */
  44. private UUID(byte[] data)
  45. {
  46. long msb = 0;
  47. long lsb = 0;
  48. assert data.length == 16 : "data must be 16 bytes in length";
  49. for (int i = 0; i < 8; i++)
  50. {
  51. msb = (msb << 8) | (data[i] & 0xff);
  52. }
  53. for (int i = 8; i < 16; i++)
  54. {
  55. lsb = (lsb << 8) | (data[i] & 0xff);
  56. }
  57. this.mostSigBits = msb;
  58. this.leastSigBits = lsb;
  59. }
  60. /**
  61. * 使用指定的数据构造新的 UUID。
  62. *
  63. * @param mostSigBits 用于 {@code UUID} 的最高有效 64 位
  64. * @param leastSigBits 用于 {@code UUID} 的最低有效 64 位
  65. */
  66. public UUID(long mostSigBits, long leastSigBits)
  67. {
  68. this.mostSigBits = mostSigBits;
  69. this.leastSigBits = leastSigBits;
  70. }
  71. /**
  72. * 获取类型 4(伪随机生成的)UUID 的静态工厂。 使用加密的本地线程伪随机数生成器生成该 UUID。
  73. *
  74. * @return 随机生成的 {@code UUID}
  75. */
  76. public static UUID fastUUID()
  77. {
  78. return randomUUID(false);
  79. }
  80. /**
  81. * 获取类型 4(伪随机生成的)UUID 的静态工厂。 使用加密的强伪随机数生成器生成该 UUID。
  82. *
  83. * @return 随机生成的 {@code UUID}
  84. */
  85. public static UUID randomUUID()
  86. {
  87. return randomUUID(true);
  88. }
  89. /**
  90. * 获取类型 4(伪随机生成的)UUID 的静态工厂。 使用加密的强伪随机数生成器生成该 UUID。
  91. *
  92. * @param isSecure 是否使用{@link SecureRandom}如果是可以获得更安全的随机码,否则可以得到更好的性能
  93. * @return 随机生成的 {@code UUID}
  94. */
  95. public static UUID randomUUID(boolean isSecure)
  96. {
  97. final Random ng = isSecure ? Holder.numberGenerator : getRandom();
  98. byte[] randomBytes = new byte[16];
  99. ng.nextBytes(randomBytes);
  100. randomBytes[6] &= 0x0f; /* clear version */
  101. randomBytes[6] |= 0x40; /* set to version 4 */
  102. randomBytes[8] &= 0x3f; /* clear variant */
  103. randomBytes[8] |= 0x80; /* set to IETF variant */
  104. return new UUID(randomBytes);
  105. }
  106. /**
  107. * 根据指定的字节数组获取类型 3(基于名称的)UUID 的静态工厂。
  108. *
  109. * @param name 用于构造 UUID 的字节数组。
  110. *
  111. * @return 根据指定数组生成的 {@code UUID}
  112. */
  113. public static UUID nameUUIDFromBytes(byte[] name)
  114. {
  115. MessageDigest md;
  116. try
  117. {
  118. md = MessageDigest.getInstance("MD5");
  119. }
  120. catch (NoSuchAlgorithmException nsae)
  121. {
  122. throw new InternalError("MD5 not supported");
  123. }
  124. byte[] md5Bytes = md.digest(name);
  125. md5Bytes[6] &= 0x0f; /* clear version */
  126. md5Bytes[6] |= 0x30; /* set to version 3 */
  127. md5Bytes[8] &= 0x3f; /* clear variant */
  128. md5Bytes[8] |= 0x80; /* set to IETF variant */
  129. return new UUID(md5Bytes);
  130. }
  131. /**
  132. * 根据 {@link #toString()} 方法中描述的字符串标准表示形式创建{@code UUID}。
  133. *
  134. * @param name 指定 {@code UUID} 字符串
  135. * @return 具有指定值的 {@code UUID}
  136. * @throws IllegalArgumentException 如果 name 与 {@link #toString} 中描述的字符串表示形式不符抛出此异常
  137. *
  138. */
  139. public static UUID fromString(String name)
  140. {
  141. String[] components = name.split("-");
  142. if (components.length != 5)
  143. {
  144. throw new IllegalArgumentException("Invalid UUID string: " + name);
  145. }
  146. for (int i = 0; i < 5; i++)
  147. {
  148. components[i] = "0x" + components[i];
  149. }
  150. long mostSigBits = Long.decode(components[0]).longValue();
  151. mostSigBits <<= 16;
  152. mostSigBits |= Long.decode(components[1]).longValue();
  153. mostSigBits <<= 16;
  154. mostSigBits |= Long.decode(components[2]).longValue();
  155. long leastSigBits = Long.decode(components[3]).longValue();
  156. leastSigBits <<= 48;
  157. leastSigBits |= Long.decode(components[4]).longValue();
  158. return new UUID(mostSigBits, leastSigBits);
  159. }
  160. /**
  161. * 返回此 UUID 的 128 位值中的最低有效 64 位。
  162. *
  163. * @return 此 UUID 的 128 位值中的最低有效 64 位。
  164. */
  165. public long getLeastSignificantBits()
  166. {
  167. return leastSigBits;
  168. }
  169. /**
  170. * 返回此 UUID 的 128 位值中的最高有效 64 位。
  171. *
  172. * @return 此 UUID 的 128 位值中最高有效 64 位。
  173. */
  174. public long getMostSignificantBits()
  175. {
  176. return mostSigBits;
  177. }
  178. /**
  179. * 与此 {@code UUID} 相关联的版本号. 版本号描述此 {@code UUID} 是如何生成的。
  180. * <p>
  181. * 版本号具有以下含意:
  182. * <ul>
  183. * <li>1 基于时间的 UUID
  184. * <li>2 DCE 安全 UUID
  185. * <li>3 基于名称的 UUID
  186. * <li>4 随机生成的 UUID
  187. * </ul>
  188. *
  189. * @return 此 {@code UUID} 的版本号
  190. */
  191. public int version()
  192. {
  193. // Version is bits masked by 0x000000000000F000 in MS long
  194. return (int) ((mostSigBits >> 12) & 0x0f);
  195. }
  196. /**
  197. * 与此 {@code UUID} 相关联的变体号。变体号描述 {@code UUID} 的布局。
  198. * <p>
  199. * 变体号具有以下含意:
  200. * <ul>
  201. * <li>0 为 NCS 向后兼容保留
  202. * <li>2 <a href="http://www.ietf.org/rfc/rfc4122.txt">IETF&nbsp;RFC&nbsp;4122</a>(Leach-Salz), 用于此类
  203. * <li>6 保留,微软向后兼容
  204. * <li>7 保留供以后定义使用
  205. * </ul>
  206. *
  207. * @return 此 {@code UUID} 相关联的变体号
  208. */
  209. public int variant()
  210. {
  211. // This field is composed of a varying number of bits.
  212. // 0 - - Reserved for NCS backward compatibility
  213. // 1 0 - The IETF aka Leach-Salz variant (used by this class)
  214. // 1 1 0 Reserved, Microsoft backward compatibility
  215. // 1 1 1 Reserved for future definition.
  216. return (int) ((leastSigBits >>> (64 - (leastSigBits >>> 62))) & (leastSigBits >> 63));
  217. }
  218. /**
  219. * 与此 UUID 相关联的时间戳值。
  220. *
  221. * <p>
  222. * 60 位的时间戳值根据此 {@code UUID} 的 time_low、time_mid 和 time_hi 字段构造。<br>
  223. * 所得到的时间戳以 100 毫微秒为单位,从 UTC(通用协调时间) 1582 年 10 月 15 日零时开始。
  224. *
  225. * <p>
  226. * 时间戳值仅在在基于时间的 UUID(其 version 类型为 1)中才有意义。<br>
  227. * 如果此 {@code UUID} 不是基于时间的 UUID,则此方法抛出 UnsupportedOperationException。
  228. *
  229. * @throws UnsupportedOperationException 如果此 {@code UUID} 不是 version 为 1 的 UUID。
  230. */
  231. public long timestamp() throws UnsupportedOperationException
  232. {
  233. checkTimeBase();
  234. return (mostSigBits & 0x0FFFL) << 48//
  235. | ((mostSigBits >> 16) & 0x0FFFFL) << 32//
  236. | mostSigBits >>> 32;
  237. }
  238. /**
  239. * 与此 UUID 相关联的时钟序列值。
  240. *
  241. * <p>
  242. * 14 位的时钟序列值根据此 UUID 的 clock_seq 字段构造。clock_seq 字段用于保证在基于时间的 UUID 中的时间唯一性。
  243. * <p>
  244. * {@code clockSequence} 值仅在基于时间的 UUID(其 version 类型为 1)中才有意义。 如果此 UUID 不是基于时间的 UUID,则此方法抛出
  245. * UnsupportedOperationException。
  246. *
  247. * @return 此 {@code UUID} 的时钟序列
  248. *
  249. * @throws UnsupportedOperationException 如果此 UUID 的 version 不为 1
  250. */
  251. public int clockSequence() throws UnsupportedOperationException
  252. {
  253. checkTimeBase();
  254. return (int) ((leastSigBits & 0x3FFF000000000000L) >>> 48);
  255. }
  256. /**
  257. * 与此 UUID 相关的节点值。
  258. *
  259. * <p>
  260. * 48 位的节点值根据此 UUID 的 node 字段构造。此字段旨在用于保存机器的 IEEE 802 地址,该地址用于生成此 UUID 以保证空间唯一性。
  261. * <p>
  262. * 节点值仅在基于时间的 UUID(其 version 类型为 1)中才有意义。<br>
  263. * 如果此 UUID 不是基于时间的 UUID,则此方法抛出 UnsupportedOperationException。
  264. *
  265. * @return 此 {@code UUID} 的节点值
  266. *
  267. * @throws UnsupportedOperationException 如果此 UUID 的 version 不为 1
  268. */
  269. public long node() throws UnsupportedOperationException
  270. {
  271. checkTimeBase();
  272. return leastSigBits & 0x0000FFFFFFFFFFFFL;
  273. }
  274. /**
  275. * 返回此{@code UUID} 的字符串表现形式。
  276. *
  277. * <p>
  278. * UUID 的字符串表示形式由此 BNF 描述:
  279. *
  280. * <pre>
  281. * {@code
  282. * UUID = <time_low>-<time_mid>-<time_high_and_version>-<variant_and_sequence>-<node>
  283. * time_low = 4*<hexOctet>
  284. * time_mid = 2*<hexOctet>
  285. * time_high_and_version = 2*<hexOctet>
  286. * variant_and_sequence = 2*<hexOctet>
  287. * node = 6*<hexOctet>
  288. * hexOctet = <hexDigit><hexDigit>
  289. * hexDigit = [0-9a-fA-F]
  290. * }
  291. * </pre>
  292. *
  293. * </blockquote>
  294. *
  295. * @return 此{@code UUID} 的字符串表现形式
  296. * @see #toString(boolean)
  297. */
  298. @Override
  299. public String toString()
  300. {
  301. return toString(false);
  302. }
  303. /**
  304. * 返回此{@code UUID} 的字符串表现形式。
  305. *
  306. * <p>
  307. * UUID 的字符串表示形式由此 BNF 描述:
  308. *
  309. * <pre>
  310. * {@code
  311. * UUID = <time_low>-<time_mid>-<time_high_and_version>-<variant_and_sequence>-<node>
  312. * time_low = 4*<hexOctet>
  313. * time_mid = 2*<hexOctet>
  314. * time_high_and_version = 2*<hexOctet>
  315. * variant_and_sequence = 2*<hexOctet>
  316. * node = 6*<hexOctet>
  317. * hexOctet = <hexDigit><hexDigit>
  318. * hexDigit = [0-9a-fA-F]
  319. * }
  320. * </pre>
  321. *
  322. * </blockquote>
  323. *
  324. * @param isSimple 是否简单模式,简单模式为不带'-'的UUID字符串
  325. * @return 此{@code UUID} 的字符串表现形式
  326. */
  327. public String toString(boolean isSimple)
  328. {
  329. final StringBuilder builder = new StringBuilder(isSimple ? 32 : 36);
  330. // time_low
  331. builder.append(digits(mostSigBits >> 32, 8));
  332. if (false == isSimple)
  333. {
  334. builder.append('-');
  335. }
  336. // time_mid
  337. builder.append(digits(mostSigBits >> 16, 4));
  338. if (false == isSimple)
  339. {
  340. builder.append('-');
  341. }
  342. // time_high_and_version
  343. builder.append(digits(mostSigBits, 4));
  344. if (false == isSimple)
  345. {
  346. builder.append('-');
  347. }
  348. // variant_and_sequence
  349. builder.append(digits(leastSigBits >> 48, 4));
  350. if (false == isSimple)
  351. {
  352. builder.append('-');
  353. }
  354. // node
  355. builder.append(digits(leastSigBits, 12));
  356. return builder.toString();
  357. }
  358. /**
  359. * 返回此 UUID 的哈希码。
  360. *
  361. * @return UUID 的哈希码值。
  362. */
  363. @Override
  364. public int hashCode()
  365. {
  366. long hilo = mostSigBits ^ leastSigBits;
  367. return ((int) (hilo >> 32)) ^ (int) hilo;
  368. }
  369. /**
  370. * 将此对象与指定对象比较。
  371. * <p>
  372. * 当且仅当参数不为 {@code null}、而是一个 UUID 对象、具有与此 UUID 相同的 varriant、包含相同的值(每一位均相同)时,结果才为 {@code true}。
  373. *
  374. * @param obj 要与之比较的对象
  375. *
  376. * @return 如果对象相同,则返回 {@code true};否则返回 {@code false}
  377. */
  378. @Override
  379. public boolean equals(Object obj)
  380. {
  381. if ((null == obj) || (obj.getClass() != UUID.class))
  382. {
  383. return false;
  384. }
  385. UUID id = (UUID) obj;
  386. return (mostSigBits == id.mostSigBits && leastSigBits == id.leastSigBits);
  387. }
  388. // Comparison Operations
  389. /**
  390. * 将此 UUID 与指定的 UUID 比较。
  391. *
  392. * <p>
  393. * 如果两个 UUID 不同,且第一个 UUID 的最高有效字段大于第二个 UUID 的对应字段,则第一个 UUID 大于第二个 UUID。
  394. *
  395. * @param val 与此 UUID 比较的 UUID
  396. *
  397. * @return 在此 UUID 小于、等于或大于 val 时,分别返回 -1、0 或 1。
  398. *
  399. */
  400. @Override
  401. public int compareTo(UUID val)
  402. {
  403. // The ordering is intentionally set up so that the UUIDs
  404. // can simply be numerically compared as two numbers
  405. return (this.mostSigBits < val.mostSigBits ? -1 : //
  406. (this.mostSigBits > val.mostSigBits ? 1 : //
  407. (this.leastSigBits < val.leastSigBits ? -1 : //
  408. (this.leastSigBits > val.leastSigBits ? 1 : //
  409. 0))));
  410. }
  411. // -------------------------------------------------------------------------------------------------------------------
  412. // Private method start
  413. /**
  414. * 返回指定数字对应的hex值
  415. *
  416. * @param val 值
  417. * @param digits 位
  418. * @return 值
  419. */
  420. private static String digits(long val, int digits)
  421. {
  422. long hi = 1L << (digits * 4);
  423. return Long.toHexString(hi | (val & (hi - 1))).substring(1);
  424. }
  425. /**
  426. * 检查是否为time-based版本UUID
  427. */
  428. private void checkTimeBase()
  429. {
  430. if (version() != 1)
  431. {
  432. throw new UnsupportedOperationException("Not a time-based UUID");
  433. }
  434. }
  435. /**
  436. * 获取{@link SecureRandom},类提供加密的强随机数生成器 (RNG)
  437. *
  438. * @return {@link SecureRandom}
  439. */
  440. public static SecureRandom getSecureRandom()
  441. {
  442. try
  443. {
  444. return SecureRandom.getInstance("SHA1PRNG");
  445. }
  446. catch (NoSuchAlgorithmException e)
  447. {
  448. throw new UtilException(e);
  449. }
  450. }
  451. /**
  452. * 获取随机数生成器对象<br>
  453. * ThreadLocalRandom是JDK 7之后提供并发产生随机数,能够解决多个线程发生的竞争争夺。
  454. *
  455. * @return {@link ThreadLocalRandom}
  456. */
  457. public static ThreadLocalRandom getRandom()
  458. {
  459. return ThreadLocalRandom.current();
  460. }
  461. }