CUniqueId.h 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #pragma once
  2. #include <atomic>
  3. #include <mutex>
  4. class CUniqueId
  5. {
  6. public:
  7. CUniqueId();
  8. CUniqueId(const unsigned char &workerId, const unsigned char &datacenterId)
  9. {
  10. _workerId = workerId;
  11. _datacenterId = datacenterId;
  12. }
  13. ~CUniqueId();
  14. private:
  15. // 开始utc时间戳(2018-01-01 00:00:00.000);
  16. const unsigned long long _twepoch = 1514736000000;
  17. // 工作者占用位数;
  18. const unsigned char _workerIdBits = 5;
  19. // 支持的最大工作者id,结果是31;
  20. const unsigned char _maxWorkerId = -1L ^ (-1L << _workerIdBits);
  21. // 数据中心占用位数;
  22. const unsigned char _datacenterIdBits = 5;
  23. // 支持的最大数据中心id,结果是31;
  24. const unsigned char _maxDatacenterId = -1L ^ (-1L << _datacenterIdBits);
  25. // 序列占用位数;
  26. const unsigned char _sequenceBits = 12;
  27. // 工作者向左移12位;
  28. const unsigned char _workerIdShift = _sequenceBits;
  29. // 数据中心向左移17位;
  30. const unsigned char _datacenterIdShift = _workerIdShift + _workerIdBits;
  31. // 时间戳向左移22位;
  32. const unsigned char _timestampleftShift = _datacenterIdShift + _datacenterIdBits;
  33. // 生成的序列掩码,4095;
  34. const unsigned short _sequenceMask = -1L ^ (-1L << _sequenceBits);
  35. // 工作id;
  36. unsigned char _workerId;
  37. // 数据中心id;
  38. unsigned char _datacenterId;
  39. // 序列值;
  40. unsigned short _sequence;
  41. // 上一次的时间戳;
  42. static unsigned long long _lasttimestamp;
  43. #ifndef USE_C0X
  44. // 如果不是c++11的话,不能使用atomic;
  45. std::mutex _mutex;
  46. #endif
  47. private:
  48. unsigned long long next_timestamp();
  49. public:
  50. void setWorkerId(const unsigned char &workerId);
  51. void setDatacenterId(const unsigned char &datacenterId);
  52. unsigned long long get_unique_id();
  53. };