post_base(標題、作者、時間) + post_stats(瀏覽數、評論數、點讚數)user_0 ... user_999uid % 1000 簡單但擴容難uid 1-10000 → t1,易熱點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 工具 |
PHP 專案若無 Java 基建,自研路由層或使用 Atlas(360 開源、基於 MySQL 協議)較輕量。