萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 生成唯一訂單號完整方案:四種演算法比較、衝突率分析與生產級推薦

訂單號核心需求

  • 全域唯一:分散式環境下零衝突
  • 可排序:按時間自然排序,利於分庫分表、查詢
  • 資訊豐富:可從號碼解析時間、業務類型、分片鍵
  • 長度適中:16-32 字元,適合資料庫索引、URL、條碼
  • 無敏感資訊:不洩露用戶 ID、金額等隱私

四種演算法深度比較

方案一:時間 + 隨機數(簡單、衝突率較高)

<?php
function orderNoV1(): string
{
    return date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
}
// 例:2024011500123
// 衝突率:同一天同毫秒內併發 > 10 萬單時衝突
// 缺點:無毫秒、無機器標識、高併發必衝突
?>

方案二:時間 + uniqid() 微秒 + 隨機(較好、但 uniqid 熵值有限)

<?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
// 優點:可驗證完整性、銀行常用格式
// 缺點:長度較長、隨機段仍有極低衝突機率
?>

方案四:時間編碼 + 機器位 + 序列號(Snowflake 風格、最強)

<?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 uniqid16秒級高日期+微秒中併發、傳統專案
V3 校驗碼24秒級中日期+時間+校驗金融、對帳需求
V4 Snowflake11-12毫秒級**零**時間+機器+序列**高併發、分散式、生產首選**

生產級推薦:Snowflake + Base36 + 字母年份前綴

<?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;

常見坑點

  1. 時鐘回撥:NTP 調整導致時間倒退,Snowflake 會拋異常,需監控並告警
  2. Machine ID 衝突:容器化部署需從 Kubernetes Downward API、Consul、Etcd 動態分配
  3. 序列號耗盡:單毫秒 > 4096 請求時阻塞,極高併發需擴展位數或分片
  4. 資料庫唯一索引:應用層生成再加 DB 唯一索引雙重保險
  5. 不要用 UUID v4:無序、36 字元、索引效能差、不可解析

訂單號是業務系統的核心標識,選對演算法、做好監控、預留擴充空間,能陪伴系統度過從萬單到億單的成長歷程。

copyright © 萬盛學電腦網 all rights reserved