Skip to content

Commit

Permalink
优化雪花ID
Browse files Browse the repository at this point in the history
  • Loading branch information
Eric committed Aug 10, 2023
1 parent 6da3a48 commit 54589fe
Showing 1 changed file with 40 additions and 13 deletions.
53 changes: 40 additions & 13 deletions src/Snowflake.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ class Snowflake
public function __construct(int $timestamp = null, int $workerId = 1, int $datacenterId = 1)
{
if ($timestamp === null) {
$timestamp = strtotime(self::DEFAULT_EPOCH_DATETIME);
$timestamp = strtotime(config('snowflake.epoch', '') ?: self::DEFAULT_EPOCH_DATETIME);
}

$this->epoch = $timestamp;
Expand All @@ -72,6 +72,39 @@ public function __construct(int $timestamp = null, int $workerId = 1, int $datac
$this->lastTimestamp = $this->epoch;
}

/**
*
* 创建实例化
*
* @return int
*/
public static function make()
{
return (new static);
}

/**
* 创建无符号bigint 64bit 唯一Id 大约可用69年.
* timestamp_bits(41) + datacenter_id_bits(5) + worker_id_bits(5) + sequence_bits(12)
*
* @return int
*/
public static function nextId(): int
{
return self::make()->id();
}

/**
* 创建兼容JS 53bit 唯一Id 大约可用68年.
* timestamp_bits(31) + datacenter_id_bits(5) + worker_id_bits(5) + sequence_bits(12)
*
* @return int
*/
public static function shortId(): int
{
return self::make()->short();
}

public function makeSequenceId(int $currentTime, int $max = self::MAX_SEQUENCE): int
{
if ($this->lastTimestamp === $currentTime) {
Expand Down Expand Up @@ -102,17 +135,6 @@ public function id(): int
return $this->toSnowflakeId($currentTime - $this->epoch * 1000, $sequenceId);
}

/**
* 创建无符号bigint 64bit 唯一Id 大约可用69年.
* timestamp_bits(41) + datacenter_id_bits(5) + worker_id_bits(5) + sequence_bits(12)
*
* @return int
*/
public static function nextId(): int
{
return (new static)->id();
}

/**
* 创建兼容JS 53bit 唯一Id 大约可用68年.
* timestamp_bits(31) + datacenter_id_bits(5) + worker_id_bits(5) + sequence_bits(12)
Expand Down Expand Up @@ -157,6 +179,11 @@ public function timestamp($microtime=true): int
}
}

public function shortParse(int $id): array
{
return $this->parse($id, true);
}

public function parse(int $id, bool $is_short=false): array
{
$id = decbin($id);
Expand Down Expand Up @@ -190,4 +217,4 @@ public function parse(int $id, bool $is_short=false): array
'datetime' => $datetime,
];
}
}
}

0 comments on commit 54589fe

Please sign in to comment.