基于php的雪花算法(snowflake)
$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));
}
}
【基于php的雪花算法(snowflake)】
推荐阅读
- 热闹中的孤独
- JAVA(抽象类与接口的区别&重载与重写&内存泄漏)
- 放屁有这三个特征的,请注意啦!这说明你的身体毒素太多
- 一个人的旅行,三亚
- 布丽吉特,人生绝对的赢家
- 慢慢的美丽
- 尽力
- 一个小故事,我的思考。
- 家乡的那条小河
- 《真与假的困惑》???|《真与假的困惑》??? ——致良知是一种伟大的力量