本文給大家聊聊雪花算法的PHP實(shí)現(xiàn),希望對(duì)需要的朋友有所幫助!
雪花算法的實(shí)現(xiàn)
最近看了下雪花算法,自己試著寫了一下
<?php class SnowFlake { const TWEPOCH = 0; // 時(shí)間起始標(biāo)記點(diǎn),作為基準(zhǔn),一般取系統(tǒng)的最近時(shí)間(一旦確定不能變動(dòng)) const WORKER_ID_BITS = 5; // 機(jī)器標(biāo)識(shí)位數(shù) const DATACENTER_ID_BITS = 5; // 數(shù)據(jù)中心標(biāo)識(shí)位數(shù) const SEQUENCE_BITS = 12; // 毫秒內(nèi)自增位 private $workerId; // 工作機(jī)器ID private $datacenterId; // 數(shù)據(jù)中心ID private $sequence; // 毫秒內(nèi)序列 private $maxWorkerId = -1 ^ (-1 << self::WORKER_ID_BITS); // 機(jī)器ID最大值 private $maxDatacenterId = -1 ^ (-1 << self::DATACENTER_ID_BITS); // 數(shù)據(jù)中心ID最大值 private $workerIdShift = self::SEQUENCE_BITS; // 機(jī)器ID偏左移位數(shù) private $datacenterIdShift = self::SEQUENCE_BITS + self::WORKER_ID_BITS; // 數(shù)據(jù)中心ID左移位數(shù) private $timestampLeftShift = self::SEQUENCE_BITS + self::WORKER_ID_BITS + self::DATACENTER_ID_BITS; // 時(shí)間毫秒左移位數(shù) private $sequenceMask = -1 ^ (-1 << self::SEQUENCE_BITS); // 生成序列的掩碼 private $lastTimestamp = -1; // 上次生產(chǎn)id時(shí)間戳 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) {//當(dāng)產(chǎn)生的時(shí)間戳小于上次的生成的時(shí)間戳?xí)r,報(bào)錯(cuò) $diffTimestamp = bcsub($this->lastTimestamp, $timestamp); throw new Exception("Clock moved backwards. Refusing to generate id for {$diffTimestamp} milliseconds"); } if ($this->lastTimestamp == $timestamp) {//當(dāng)生成的時(shí)間戳等于上次生成的時(shí)間戳的時(shí)候 $this->sequence = ($this->sequence + 1) & $this->sequenceMask;//序列自增一次 if (0 == $this->sequence) {//當(dāng)序列為0時(shí),重新生成最新的時(shí)間戳 $timestamp = $this->createNextTimestamp($this->lastTimestamp); } } else {//當(dāng)生成的時(shí)間戳不等于上次的生成的時(shí)間戳的時(shí)候,序列歸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) //生成一個(gè)大于等于 上次生成的時(shí)間戳 的時(shí)間戳 { $timestamp = $this->createTimestamp(); while ($timestamp <= $lastTimestamp) { $timestamp = $this->createTimestamp(); } return $timestamp; } protected function createTimestamp()//生成毫秒級(jí)別的時(shí)間戳 { return floor(microtime(true) * 1000); } } ?>
推薦學(xué)習(xí):《PHP視頻教程》