BizCodeUtil.java 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package com.usoft.bizcode.utils;
  2. import org.apache.commons.lang3.StringUtils;
  3. /**
  4. * 业务号 工具类
  5. *
  6. * @author: wangcanyi
  7. * @date: 2018-08-23 16:51
  8. **/
  9. public class BizCodeUtil {
  10. private static final int BIZ_CODE_MAX_LENGTH = 10;
  11. private static final int PREFIX_LENGTH = 2;
  12. private static final int SE_MAX = 9;
  13. private static final int SE_LENGTH = 1;
  14. private static int se = 0;
  15. /**
  16. * 创建业务号 最长10位
  17. *
  18. * @param prefix 前缀 - 自定义 - 长度:2位
  19. * @return
  20. */
  21. public static String genBizCode(String prefix) {
  22. if (StringUtils.isBlank(prefix)) {
  23. throw new IllegalArgumentException("prefix不能为空");
  24. }
  25. if (prefix.length() != PREFIX_LENGTH) {
  26. throw new IllegalArgumentException("prefix长度必须为2位");
  27. }
  28. synchronized (BizCodeUtil.class) {
  29. String nextCode;
  30. if (se > SE_MAX) {
  31. se = 0;
  32. }
  33. //当前精确到0.1毫秒
  34. String decimalCode = "" + System.currentTimeMillis() + createSerial("" + se, SE_LENGTH);
  35. //10进制转62进制
  36. nextCode = DecimalConverter.fromDecimal(decimalCode, 62);
  37. se++;
  38. if (nextCode.length() > BIZ_CODE_MAX_LENGTH) {
  39. throw new RuntimeException("生成业务号长度错误[" + nextCode + "]");
  40. }
  41. return prefix + nextCode;
  42. }
  43. }
  44. /**
  45. * 生成固定长度的序列号,不足位数在前补0
  46. *
  47. * @param src
  48. * @param len
  49. * @return
  50. */
  51. private static String createSerial(String src, int len) {
  52. String dest = "";
  53. if (src.length() >= len) {
  54. dest = src.substring(0, len);
  55. } else {
  56. dest = createSameChar("0", len - src.length()) + src;
  57. }
  58. return dest;
  59. }
  60. /**
  61. * 返回相同字符的串
  62. */
  63. private static String createSameChar(String src, int len) {
  64. StringBuffer sb = new StringBuffer();
  65. for (int i = 0; i < len; i++) {
  66. sb.append(src);
  67. }
  68. return sb.toString();
  69. }
  70. }