8b531e4697a871b539ba6921cecd7a572eb590a9.svn-base 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package org.jeecg.common.util;
  2. import java.net.InetAddress;
  3. /**
  4. *
  5. * @Author 张代浩
  6. *
  7. */
  8. public class UUIDGenerator {
  9. /**
  10. * 产生一个32位的UUID
  11. *
  12. * @return
  13. */
  14. public static String generate() {
  15. return new StringBuilder(32).append(format(getIP())).append(
  16. format(getJVM())).append(format(getHiTime())).append(
  17. format(getLoTime())).append(format(getCount())).toString();
  18. }
  19. private static final int IP;
  20. static {
  21. int ipadd;
  22. try {
  23. ipadd = toInt(InetAddress.getLocalHost().getAddress());
  24. } catch (Exception e) {
  25. ipadd = 0;
  26. }
  27. IP = ipadd;
  28. }
  29. private static short counter = (short) 0;
  30. private static final int JVM = (int) (System.currentTimeMillis() >>> 8);
  31. private final static String format(int intval) {
  32. String formatted = Integer.toHexString(intval);
  33. StringBuilder buf = new StringBuilder("00000000");
  34. buf.replace(8 - formatted.length(), 8, formatted);
  35. return buf.toString();
  36. }
  37. private final static String format(short shortval) {
  38. String formatted = Integer.toHexString(shortval);
  39. StringBuilder buf = new StringBuilder("0000");
  40. buf.replace(4 - formatted.length(), 4, formatted);
  41. return buf.toString();
  42. }
  43. private final static int getJVM() {
  44. return JVM;
  45. }
  46. private final static short getCount() {
  47. synchronized (UUIDGenerator.class) {
  48. if (counter < 0) {
  49. counter = 0;
  50. }
  51. return counter++;
  52. }
  53. }
  54. /**
  55. * Unique in a local network
  56. */
  57. private final static int getIP() {
  58. return IP;
  59. }
  60. /**
  61. * Unique down to millisecond
  62. */
  63. private final static short getHiTime() {
  64. return (short) (System.currentTimeMillis() >>> 32);
  65. }
  66. private final static int getLoTime() {
  67. return (int) System.currentTimeMillis();
  68. }
  69. private final static int toInt(byte[] bytes) {
  70. int result = 0;
  71. for (int i = 0; i < 4; i++) {
  72. result = (result << 8) - Byte.MIN_VALUE + (int) bytes[i];
  73. }
  74. return result;
  75. }
  76. }