雪花算法php实现


nodeId > self::WORKER_MAX) { trigger_error("Worker ID 超出范围"); exit(0); } $this->timestamp = 0; $this->nodeId = $nodeId; $this->sequence = 0; } /** * 生成ID * @return int */ public function getId() { $now = $this->now(); if ($this->timestamp == $now) { $this->sequence++; if ($this->sequence > self::SEQUENCE_MAX) { // 当前毫秒内生成的序号已经超出最大范围,等待下一毫秒重新生成 while ($now <= $this->timestamp) { $now = $this->now(); } } } else { $this->sequence = 0; } $this->timestamp = $now; // 更新ID生时间戳 $id = (($now - self::EPOCH) << self::TIME_SHIFT) | ($this->nodeId << self::WORKER_SHIFT) | $this->sequence; return $id; } /** * 获取当前毫秒 * @return string */ public function now() { return sprintf("%.0f", microtime(true) * 1000); } }

文章作者: Bob
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Bob !
  目录