分库和分表

本文介绍了一款针对2亿用户设计的地址簿应用程序如何通过分库分表技术处理庞大的数据量。采用MD5算法对用户邮箱进行哈希运算,并通过取余操作将数据均匀分配到1000张表中,每张表再分布于100个数据库中,以降低单一数据库的压力。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1,背景:一个地址薄的应用程序,设计的用户量为2亿,统计出每个用户的地址薄为30个左右,整个数据量为60亿,使用mysql数据库
计划分为:1000个表,100个库

2,分库分表代码

private function getDbNo($email)
{
$m = md5($email);
$n = hexdec(substr($m, 0, 16));
$tableNo = fmod($n, 1000);
$dbNo = $tableNo % 100;
return array($dbNo, $tableNo);
}

3,配合的连接访问代码

require_once 'Db/Config.php';

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

private static $instances = array();

private $conf = array();

private $conns = array();

private $conn = NULL;
private $stmt = NULL;

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

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

$conn->prepare($sql);
$stmt = $conn->execute($params);

$this->conn = $conn;
$this->stmt = $stmt;
}

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)
{
if ($type == self::SLAVE && isset($this->conf[self::SLAVE])) {
$id = 0;
} else {
$id = 1;
}

if (!isset($this->conns[$id])) {
$conf = $this->conf[$id];
$this->conns[$id] = new PDO(
$conf['dsn'], $conf['user'], $conf['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];
}
}


4,潜在问题
如果某个表中的那些用户的地址薄联系人超多,如每个人1000个,则可能出现该表超大,需要把该表区分为子表,暂时没有配置中心来处理该情况。
(若真的出现该情况,在连接参数这个地方继续作一次hash)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值