VisibleIdCreater.java 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package com.diagbot.idc;
  2. import com.diagbot.enums.VisibleIdTypeEnum;
  3. import com.diagbot.util.DateUtil;
  4. import lombok.extern.slf4j.Slf4j;
  5. import org.apache.commons.lang3.RandomUtils;
  6. import org.apache.commons.lang3.time.DateUtils;
  7. import java.util.Calendar;
  8. /**
  9. * @Description: 可见id每秒递增
  10. * @author: gaodm
  11. * @time: 2018/9/5 10:45
  12. */
  13. @Slf4j
  14. public class VisibleIdCreater extends AbstractIdCreater<Integer> {
  15. private long lastTimestamp = -1L;
  16. private long sequence = 0L;
  17. private long sequenceMask = 9999;
  18. public VisibleIdCreater(int machineId, int dataCenterId) {
  19. super(machineId, dataCenterId);
  20. }
  21. /**
  22. * 对外id生成规则
  23. * 1809051234550001
  24. * 180905 - 12345 - 1 - 0001
  25. * 日期 - 秒数 - 业务 - 秒内自增
  26. *
  27. * @param type 业务id 1.订单 2.交易 3.退款
  28. * @return 生成的id
  29. */
  30. @Override
  31. public synchronized Long getNextId(Integer type) {
  32. Calendar calendar = Calendar.getInstance();
  33. long timestamp = timeGen() / 1000;
  34. if (timestamp < lastTimestamp) {
  35. log.error(String.format("clock is moving backwards. Rejecting requests until %d.", lastTimestamp));
  36. throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
  37. }
  38. if (lastTimestamp == timestamp) {
  39. sequence = (sequence + 1);
  40. if (sequence > sequenceMask) {
  41. //timestamp = tilNextMillis(lastTimestamp);
  42. log.error(String.format("id creater sequence is full. wait to next time"));
  43. return null;
  44. }
  45. } else {
  46. sequence = getNewSequence();
  47. }
  48. lastTimestamp = timestamp;
  49. String date = DateUtil.format(calendar.getTime(), "yyMMdd");
  50. long seconds = DateUtils.getFragmentInSeconds(calendar, Calendar.DAY_OF_YEAR);
  51. return Long.valueOf(date + String.format("%05d", seconds) + String.valueOf(type) + sequence);
  52. }
  53. private long getNewSequence() {
  54. return RandomUtils.nextInt(1000, 2000);
  55. }
  56. public static void main(String[] args) {
  57. VisibleIdCreater visibleIdCreater = new VisibleIdCreater(0, 0);
  58. System.out.println(visibleIdCreater.getNextId(VisibleIdTypeEnum.PATIENT_NO.getKey()));
  59. }
  60. }