最近看了下雪花演算法,自己試著寫了一下
<?php
class SnowFlake
{
const TWEPOCH = 0; // 時間起始標記點,作為基準,一般取系統的最近時間(一旦確定不能變動)
const WORKER_ID_BITS = 5; // 機器標識位數
const DATACENTER_ID_BITS = 5; // 資料中心標識位數
const SEQUENCE_BITS = 12; // 毫秒內自增位
private $workerId; // 工作機器ID
private $datacenterId; // 資料中心ID
private $sequence; // 毫秒內序列
private $maxWorkerId = -1 ^ (-1 << self::WORKER_ID_BITS); // 機器ID最大值
private $maxDatacenterId = -1 ^ (-1 << self::DATACENTER_ID_BITS); // 資料中心ID最大值
private $workerIdShift = self::SEQUENCE_BITS; // 機器ID偏左移位數
private $datacenterIdShift = self::SEQUENCE_BITS + self::WORKER_ID_BITS; // 資料中心ID左移位數
private $timestampLeftShift = self::SEQUENCE_BITS + self::WORKER_ID_BITS + self::DATACENTER_ID_BITS; // 時間毫秒左移位數
private $sequenceMask = -1 ^ (-1 << self::SEQUENCE_BITS); // 生成序列的掩碼
private $lastTimestamp = -1; // 上次生產id時間戳
public function __construct($workerId, $datacenterId, $sequence = 0)
{
if ($workerId > $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);
}
}
?>
本作品採用《CC 協議》,轉載必須註明作者和本文連結