1. 程式人生 > 實用技巧 >php版雪花演算法生產唯一ID

php版雪花演算法生產唯一ID

<?php
class SnowFlake
{
    const TWEPOCH = 1288834974657; // 時間起始標記點,作為基準,一般取系統的最近時間(一旦確定不能變動)

    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 nextId() { $timestamp = $this->timeGen(); 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) { $timestamp = $this->tilNextMillis($this->lastTimestamp); } } else { $this->sequence = 0; } $this->lastTimestamp = $timestamp; /*$gmpTimestamp = gmp_init($this->leftShift(bcsub($timestamp, self::TWEPOCH), $this->timestampLeftShift)); $gmpDatacenterId = gmp_init($this->leftShift($this->datacenterId, $this->datacenterIdShift)); $gmpWorkerId = gmp_init($this->leftShift($this->workerId, $this->workerIdShift)); $gmpSequence = gmp_init($this->sequence); return gmp_strval(gmp_or(gmp_or(gmp_or($gmpTimestamp, $gmpDatacenterId), $gmpWorkerId), $gmpSequence));*/ return (($timestamp - self::TWEPOCH) << $this->timestampLeftShift) | ($this->datacenterId << $this->datacenterIdShift) | ($this->workerId << $this->workerIdShift) | $this->sequence; } protected function tilNextMillis($lastTimestamp) { $timestamp = $this->timeGen(); while ($timestamp <= $lastTimestamp) { $timestamp = $this->timeGen(); } return $timestamp; } protected function timeGen() { return floor(microtime(true) * 1000); } // 左移 << protected function leftShift($a, $b) { return bcmul($a, bcpow(2, $b)); } }