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