本文给大家聊聊雪花算法的php实现,希望对需要的朋友有所帮助!
雪花算法的实现
最近看了下雪花算法,自己试着写了一下
$this->maxWorkerId || $workerId < 0) {
throw new Exception("worker Id can't be greater than {$this->maxWorkerId} or less than 0");
}
if ($datacenterId > $this->maxDatacenterId || $datacenterId < 0) {
throw new Exception("datacenter Id can't be greater than {$this->maxDatacenterId} or less than 0");
}
$this->workerId = $workerId;
$this->datacenterId = $datacenterId;
$this->sequence = $sequence;
}
public function createId()
{
$timestamp = $this->createTimestamp();
if ($timestamp < $this->lastTimestamp) {//当产生的时间戳小于上次的生成的时间戳时,报错
$diffTimestamp = bcsub($this->lastTimestamp, $timestamp);
throw new Exception("Clock moved backwards. Refusing to generate id for {$diffTimestamp} milliseconds");
}
if ($this->lastTimestamp == $timestamp) {//当生成的时间戳等于上次生成的时间戳的时候
$this->sequence = ($this->sequence + 1) & $this->sequenceMask;//序列自增一次
if (0 == $this->sequence) {//当序列为0时,重新生成最新的时间戳
$timestamp = $this->createNextTimestamp($this->lastTimestamp);
}
} else {//当生成的时间戳不等于上次的生成的时间戳的时候,序列归0
$this->sequence = 0;
}
$this->lastTimestamp = $timestamp;
return (($timestamp - self::TWEPOCH) << $this->timestampLeftShift) |
($this->datacenterId << $this->datacenterIdShift) |
($this->workerId << $this->workerIdShift) |
$this->sequence;
}
protected function createNextTimestamp($lastTimestamp) //生成一个大于等于 上次生成的时间戳 的时间戳
{
$timestamp = $this->createTimestamp();
while ($timestamp <= $lastTimestamp) {
$timestamp = $this->createTimestamp();
}
return $timestamp;
}
protected function createTimestamp()//生成毫秒级别的时间戳
{
return floor(microtime(true) * 1000);
}
}
?>推荐学习:《PHP视频教程》











