CodeGenerator.java 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package com.uas.kanban.util;
  2. import java.util.Calendar;
  3. import java.util.Date;
  4. /**
  5. * 生成唯一 code
  6. *
  7. * @author sunyj
  8. * @since 2017年8月22日 上午11:34:44
  9. */
  10. public class CodeGenerator {
  11. private final static int MAX_OFFSET = 16 * 16 - 16;
  12. /**
  13. * 生成 code 时的偏移量
  14. */
  15. private static int offset = 0;
  16. private static CodeGenerator generator;
  17. private CodeGenerator() {
  18. }
  19. public static CodeGenerator getGenerator() {
  20. if (generator == null) {
  21. synchronized (CodeGenerator.class) {
  22. if (generator == null) {
  23. generator = new CodeGenerator();
  24. }
  25. }
  26. }
  27. return generator;
  28. }
  29. /**
  30. * 生成唯一 code (一秒内不超过 {@link CodeGenerator#MAX_OFFSET} 个,超过则不唯一)
  31. */
  32. public synchronized String generate() {
  33. // 偏移量,不超过 MAX_OFFSET 个
  34. offset = (offset + 1) % MAX_OFFSET + 16;
  35. // 当前毫秒数
  36. long now = new Date().getTime();
  37. // 起始时间 2017-01-01 00:00:00:000
  38. Calendar startCalendar = Calendar.getInstance();
  39. startCalendar.set(2017, 0, 1, 0, 0, 0);
  40. startCalendar.set(Calendar.MILLISECOND, 0);
  41. // 偏移量加16,保证得到的是两位16进制字符
  42. String hex = Long.toHexString(now - startCalendar.getTimeInMillis()) + Integer.toHexString(offset);
  43. // 最后反转并转为大写
  44. return hex.toUpperCase();
  45. }
  46. }