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);
}
}