SnowflakeIdGenerator.hpp 659 B

12345678910111213141516171819202122
  1. #include <stdint.h>
  2. class SnowflakeIdGenerator {
  3. public:
  4. SnowflakeIdGenerator(uint32_t workerId, uint32_t machineId)
  5. : workerId_(workerId), machineId_(machineId), sequence_(0) {}
  6. uint64_t nextId() {
  7. static uint64_t timestamp = time(NULL);
  8. uint64_t id = 0;
  9. // 生成id的计算公式为: Timestamp左移4位 | 机器ID左移20位 | 机器ID右移12位 | 工作ID右移13位 | 序数
  10. id = (timestamp << 4) | (machineId_ << 20) | (machineId_ >> 12) | (workerId_ >> 13) | sequence_++;
  11. return id;
  12. }
  13. private:
  14. uint32_t workerId_;
  15. uint32_t machineId_;
  16. uint32_t sequence_;
  17. };