萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 資料庫 >> MySQL 教學

MySQL 海量資料分庫分表實戰:PHP 路由層實作與避坑指南

分庫分表核心策略

  1. 主從複寫 + 讀寫分離: 主庫寫、從庫讀,一主多從分攤讀壓力
  2. 業務垂直分庫: 依業務域拆分(用戶庫、訂單庫、日誌庫)
  3. 水平分表: 單表超過 1000-2000 萬行時,按鍵值分散到同結構多表

分表類型詳解

縱向分表(垂直拆分欄位)

  • 依資料活躍度拆分:冷熱分離
  • 範例:部落格系統 → post_base(標題、作者、時間) + post_stats(瀏覽數、評論數、點讚數)
  • 優勢:
    • 冷資料用 MyISAM 壓縮查詢快
    • 熱資料用 InnoDB 寫入快
    • 分別配置主從比例

橫向分表(水平拆分資料)

  • 依分片鍵將同結構資料分散到多表:user_0 ... user_999
  • 常見分片演算法:
    • 取模: uid % 1000 簡單但擴容難
    • 一致性雜湊: 擴容遷移資料少
    • 範圍分片: uid 1-10000 → t1,易熱點
    • MD5 雜湊: 分布均勻,支援任意擴容

PHP 路由層實作範例

分片演算法(MD5 + 雙層映射)

private function getDbNo($email) {
    $m = md5($email);
    $n = hexdec(substr($m, 0, 16));          // 取前 16 字元轉 64 位整數
    $tableNo = fmod($n, 1000);               // 1000 張表
    $dbNo = $tableNo % 100;                  // 100 個庫
    return [$dbNo, $tableNo];
}

資料庫連接適配器(支援主從自動路由)

require_once 'Db/Config.php';

class Db_Adapter {
    const MASTER = 0;
    const SLAVE  = 1;

    private static $instances = [];
    private $conf = [];
    private $conns = [];
    private $conn = null;
    private $stmt = null;

    public function __construct($conf) { $this->conf = $conf; }

    public function execute($sql, $params) {
        $cmd = strtolower(trim(substr($sql, 0, 6)));
        $conn = $this->getConn($cmd === 'select' ? self::SLAVE : self::MASTER);
        $this->stmt = $conn->prepare($sql);
        $this->stmt->execute($params);
        $this->conn = $conn;
    }

    public function fetch() { return $this->stmt->fetch(); }
    public function fetchAll() { return $this->stmt->fetchAll(); }
    public function lastInsertId($name = null) { return $this->conn->lastInsertId($name); }
    public function rowCount() { return $this->stmt->rowCount(); }

    private function getConn($type) {
        $id = ($type === self::SLAVE && isset($this->conf[self::SLAVE])) ? 0 : 1;
        if (!isset($this->conns[$id])) {
            $c = $this->conf[$id];
            $this->conns[$id] = new PDO($c['dsn'], $c['user'], $c['pass'], self::dbOptions);
        }
        return $this->conns[$id];
    }

    public static function getInstance($dbName, $dbNo = 0) {
        $key = $dbName . '_' . $dbNo;
        if (!isset(self::$instances[$key])) {
            $conf = Db_Config::getConfig($dbName, $dbNo);
            self::$instances[$key] = new self($conf);
        }
        return self::$instances[$key];
    }
}

使用範例

$adapter = Db_Adapter::getInstance('user_db', $dbNo);
$adapter->execute("SELECT * FROM user_{$tableNo} WHERE email = ?", [$email]);
$user = $adapter->fetch();

潛在問題與演進方向

問題影響解決方案
熱點鍵值導致單表過大查詢/寫入效能劣化二級分片:熱點表再按子鍵拆分
跨分片 JOIN/事務無法直接支援應用層組裝、最終一致性、Saga 模式
全域唯一 ID自增 ID 衝突Snowflake、UUID、段號模式
擴容遷移資料重新分佈雙寫同步、影子表、線上 DDL 工具

中間件替代方案

  • ShardingSphere / Sharding-JDBC: Java 生態完整
  • Mycat / Cobar: 代理層透明分片
  • Vitess: YouTube 開源,支援 Kubernetes 原生
  • ProxySQL + Query Rules: 輕量級路由

PHP 專案若無 Java 基建,自研路由層或使用 Atlas(360 開源、基於 MySQL 協議)較輕量。

copyright © 萬盛學電腦網 all rights reserved