<?php
function orderNoV1(): string
{
return date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
}
// 例:2024011500123
// 衝突率:同一天同毫秒內併發 > 10 萬單時衝突
// 缺點:無毫秒、無機器標識、高併發必衝突
?>
<?php
function orderNoV2(): string
{
return date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
}
// 例:2024011512345678
// 衝突率:同微秒併發極高時可能衝突
?>
<?php
function orderNoV3(): string
{
date_default_timezone_set('PRC');
$main = date('YmdHis') . random_int(10000000, 99999999); // 14+8=22 位
$sum = array_sum(str_split($main));
$check = str_pad((100 - $sum % 100) % 100, 2, '0', STR_PAD_LEFT);
return $main . $check; // 24 位:YYYYMMDDHHIISS + 8隨機 + 2校驗
}
// 例:202401151230458765432109
// 優點:可驗證完整性、銀行常用格式
// 缺點:長度較長、隨機段仍有極低衝突機率
?>
<?php
class OrderNoGenerator
{
private int $machineId; // 0-31 (5 bits)
private int $sequence = 0;
private int $lastTime = 0;
public function __construct(int $machineId = 0)
{
if ($machineId < 0 || $machineId > 31) throw new InvalidArgumentException('machineId 0-31');
$this->machineId = $machineId;
}
public function generate(): string
{
$now = $this->currentTimeMillis();
if ($now < $this->lastTime) {
throw new RuntimeException('Clock moved backwards');
}
if ($now === $this->lastTime) {
$this->sequence = ($this->sequence + 1) & 0xFFF; // 12 bits = 4096
if ($this->sequence === 0) {
// 同毫秒序列耗盡,等待下一毫秒
$now = $this->waitNextMillis($this->lastTime);
}
} else {
$this->sequence = 0;
}
$this->lastTime = $now;
// 組裝:41bits時間(毫秒) + 5bits機器 + 12bits序列 = 58 bits
// 轉為 36 進制縮短長度
$id = (($now - 1609459200000) << 17) | ($this->machineId << 12) | $this->sequence;
return $this->toBase36($id); // 約 11-12 字元
}
private function currentTimeMillis(): int
{
return (int)(microtime(true) * 1000);
}
private function waitNextMillis(int $lastTime): int
{
$now = $this->currentTimeMillis();
while ($now <= $lastTime) {
usleep(100);
$now = $this->currentTimeMillis();
}
return $now;
}
private function toBase36(int $num): string
{
$chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$result = '';
while ($num > 0) {
$result = $chars[$num % 36] . $result;
$num = (int)($num / 36);
}
return str_pad($result, 12, '0', STR_PAD_LEFT);
}
}
// 使用:每台伺服器配置不同 machineId
$gen1 = new OrderNoGenerator(1);
$gen2 = new OrderNoGenerator(2);
echo $gen1->generate(); // 如:000001A2B3C4
echo $gen2->generate(); // 如:000001A2B3C5
?>
| 方案 | 長度 | 可排序 | 衝突率(萬QPS) | 可解析資訊 | 適用場景 |
|---|---|---|---|---|---|
| V1 時間+隨機 | 13 | 日級 | 極高 | 日期 | 低併發、內部單據 |
| V2 uniqid | 16 | 秒級 | 高 | 日期+微秒 | 中併發、傳統專案 |
| V3 校驗碼 | 24 | 秒級 | 中 | 日期+時間+校驗 | 金融、對帳需求 |
| V4 Snowflake | 11-12 | 毫秒級 | **零** | 時間+機器+序列 | **高併發、分散式、生產首選** |
<?php
class OrderNumber
{
private OrderNoGenerator $generator;
private array $yearCode = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P']; // 2020-2035
public function __construct(int $machineId = 0)
{
$this->generator = new OrderNoGenerator($machineId);
}
public function generate(string $bizType = ''): string
{
$yearIdx = (int)date('Y') - 2020;
$prefix = $this->yearCode[$yearIdx] ?? 'Z';
$biz = $bizType ? strtoupper(substr($bizType, 0, 2)) : '';
return $prefix . $biz . $this->generator->generate();
}
public function parse(string $orderNo): array
{
$prefix = $orderNo[0];
$year = 2020 + array_search($prefix, $this->yearCode);
$biz = substr($orderNo, 1, 2);
$id = substr($orderNo, 3);
$decoded = $this->fromBase36($id);
$sequence = $decoded & 0xFFF;
$machineId = ($decoded >> 12) & 0x1F;
$timestamp = ($decoded >> 17) + 1609459200000; // 2021-01-01 00:00:00 UTC
return [
'year' => $year,
'biz_type' => $biz,
'machine_id' => $machineId,
'sequence' => $sequence,
'timestamp' => $timestamp,
'datetime' => date('Y-m-d H:i:s.u', $timestamp / 1000),
];
}
private function fromBase36(string $str): int
{
$chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$num = 0;
for ($i = 0; $i < strlen($str); $i++) {
$num = $num * 36 + strpos($chars, $str[$i]);
}
return $num;
}
}
// 使用
$gen = new OrderNumber(machineId: 5);
$no = $gen->generate('ORD'); // AORD000001A2B3C4
print_r($gen->parse($no));
/*
Array
(
[year] => 2024
[biz_type] => OR
[machine_id] => 5
[sequence] => 1234
[timestamp] => 1705312245123
[datetime] => 2024-01-15 12:30:45.123
)
*/
?>
CREATE TABLE `orders` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`order_no` CHAR(16) NOT NULL COMMENT '業務訂單號',
`order_no_prefix` CHAR(3) GENERATED ALWAYS AS (LEFT(`order_no`, 3)) STORED,
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
PRIMARY KEY (`id`),
UNIQUE KEY `uk_order_no` (`order_no`),
INDEX `idx_prefix_time` (`order_no_prefix`, `created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
訂單號是業務系統的核心標識,選對演算法、做好監控、預留擴充空間,能陪伴系統度過從萬單到億單的成長歷程。