1. 程式人生 > 其它 >snowflake 雪花演算法 php中 使用demo

snowflake 雪花演算法 php中 使用demo

<?php
/**
 * Snowflake 生成唯一ID演算法,固定返回19位
 * User: zc
 * Date: 2020/7/22
 * Time: 15:29
 */
define('EPOCH',1024528659185); // 當前時間(毫秒)
define('NUMWORKERBITS', 10);
define('NUMSEQUENCEBITS', 12);
define('MAXWORKERID', (-1 ^ (-1 << NUMWORKERBITS)));    // 叢集ID + 機器ID, 10位,最多支援1024臺機器
define('MAXSEQUENCE', (-1 ^ (-1 << NUMSEQUENCEBITS)));  //
序列,12位,每臺機器每毫秒內最多產生4096個序列號 class Snowflake { private $_lastTimestamp; private $_sequence = 0; private $_workerId = 1; public function __construct($workerId=1) { if (($workerId < 0) || ($workerId > MAXWORKERID)) { return null; } $this->_workerId = $workerId
; } public function next() { $ts = $this->timestamp(); if ($ts == $this->_lastTimestamp) { $this->_sequence = ($this->_sequence + 1) & MAXSEQUENCE; if ($this->_sequence == 0) { $ts = $this->waitNextMilli($ts); } }
else { $this->_sequence = 0; } if ($ts < $this->_lastTimestamp) { return 0; } $this->_lastTimestamp = $ts; $return_pack = $this->pack(); if(strlen($return_pack) < 19) $return_pack = str_pad($return_pack, 19, '0'); return $return_pack; } private function pack() { return ($this->_lastTimestamp << (NUMWORKERBITS + NUMSEQUENCEBITS)) | ($this->_workerId << NUMSEQUENCEBITS) | $this->_sequence; } private function waitNextMilli($ts) { if ($ts = $this->_lastTimestamp) { sleep(0.1); $ts = $this->timestamp(); } return $ts; } private function timestamp() { return $this->millitime() - EPOCH; } private function millitime() { $microtime = microtime(); $comps = explode(' ', $microtime); return sprintf('%d%03d', $comps[1], $comps[0] * 1000); } }
 $snowflake = new Snowflake();
 $card = $snowflake->next();
 var_dump($card );