UUID.java 15 KB

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