PHP 雪花算法

 $this->maxWorkerId || $workerId < 0) {
//            throw new \Exception("wechat 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;
//    }

    /**
     * 生产唯一id号
     * @return string
     * @throws \Exception
     */
    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));
    }

    /**
     * @param $lastTimestamp
     * @return false|float
     */
    protected function tilNextMillis($lastTimestamp)
    {
        $timestamp = $this->timeGen();
        while ($timestamp <= $lastTimestamp) {
            $timestamp = $this->timeGen();
        }
        return $timestamp;
    }

    /**
     * @return false|float
     */
    protected function timeGen()
    {
        return floor(microtime(true) * 1000);
    }

    /**
     * 左移 <<
     * @param $a
     * @param $b
     * @return string
     */
    protected function leftShift($a, $b)
    {
        return bcmul($a, bcpow(2, $b));
    }


}

你可能感兴趣的:(php,算法)