本文实例讲述了Yii实现多数据库主从读写分离的方法。分享给大家供大家参考。具体分析如下:
Yii框架数据库多数据库、主从、读写分离 实现,功能描述:
1.实现主从数据库读写分离 主库:写 从库(可多个):读
2.主数据库无法连接时 可设置从数据库是否 可写
3.所有从数据库无法连接时 可设置主数据库是否 可读
4.如果从数据库连接失败 可设置N秒内不再连接
利用yii扩展实现,代码如下:
复制代码 代码如下:<"Master db server is not available now!Disallow write operation on slave server!");
}
}
return parent::createCommand($sql);
}
}
/**
* 获得从服务器连接资源
* @return CDbConnection
* */
public function getSlave() {
if (!isset($this->_slave)) {
shuffle($this->slaves);
foreach ($this->slaves as $slaveConfig) {
if ($this->_isDeadServer($slaveConfig['connectionString'])) {
continue;
}
if (!isset($slaveConfig['class']))
$slaveConfig['class'] = 'CDbConnection';
$slaveConfig['autoConnect'] = false;
try {
if ($slave = Yii::createComponent($slaveConfig)) {
Yii::app()->setComponent('dbslave', $slave);
$slave->setAttribute(PDO::ATTR_TIMEOUT, $this->timeout);
$slave->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
$slave->setActive(true);
$this->_slave = $slave;
break;
}
} catch (Exception $e) {
$this->_markDeadServer($slaveConfig['connectionString']);
Yii::log("Slave database connection failed!ntConnection string:{$slaveConfig['connectionString']}", 'warning');
continue;
}
}
if (!isset($this->_slave)) {
$this->_slave = null;
$this->enableSlave = false;
}
}
return $this->_slave;
}
public function setActive($value) {
if ($value != $this->getActive()) {
if ($value) {
try {
if ($this->_isDeadServer($this->connectionString)) {
throw new CDbException('Master db server is already dead!');
}
//PDO::ATTR_TIMEOUT must set before pdo instance create
$this->setAttribute(PDO::ATTR_TIMEOUT, $this->timeout);
$this->open();
} catch (Exception $e) {
$this->_markDeadServer($this->connectionString);
$slave = $this->getSlave();
Yii::log($e->getMessage(), CLogger::LEVEL_ERROR, 'exception.CDbException');
if ($slave) {
$this->connectionString = $slave->connectionString;
$this->username = $slave->username;
$this->password = $slave->password;
if ($this->slavesWrite) {
$this->_disableWrite = false;
}
$this->open();
} else { //Slave also unavailable
if ($this->masterRead) {
$this->connectionString = $this->connectionString;
$this->username = $this->username;
$this->password = $this->password;
$this->open();
} else {
throw new CDbException(Yii::t('yii', 'CDbConnection failed to open the DB connection.'), (int) $e->getCode(), $e->errorInfo);
}
}
}
} else {
$this->close();
}
}
}
/**
* 检测读操作 sql 语句
*
* 关键字: SELECT,DECRIBE,SHOW ...
* 写操作:UPDATE,INSERT,DELETE ...
* */
public static function isReadOperation($sql) {
$sql = substr(ltrim($sql), 0, 10);
$sql = str_ireplace(array('SELECT', 'SHOW', 'DESCRIBE', 'PRAGMA'), '^O^', $sql); //^O^,magic smile
return strpos($sql, '^O^') === 0;
}
/**
* 检测从服务器是否被标记 失败.
*/
private function _isDeadServer($c) {
$cache = Yii::app()->{$this->cacheID};
if ($cache && $cache->get('DeadServer::' . $c) == 1) {
return true;
}
return false;
}
/**
* 标记失败的slaves.
*/
private function _markDeadServer($c) {
$cache = Yii::app()->{$this->cacheID};
if ($cache) {
$cache->set('DeadServer::' . $c, 1, $this->markDeadSeconds);
}
}
}
main.php配置:components 数组中,代码如下:
复制代码 代码如下:'db'=>array(
'class'=>'application.extensions.DbConnectionMan',//扩展路径
'connectionString' => 'mysql:host=192.168.1.128;dbname=db_xcpt',//主数据库 写
'emulatePrepare' => true,
'username' => 'root',
'password' => 'root',
'charset' => 'utf8',
'tablePrefix' => 'xcpt_', //表前缀
'enableSlave'=>true,//从数据库启用
'urgencyWrite'=>true,//紧急情况 主数据库无法连接 启用从数据库 写功能
'masterRead'=>true,//紧急情况 从数据库无法连接 启用主数据库 读功能
'slaves'=>array(//从数据库
array( //slave1
'connectionString'=>'mysql:host=localhost;dbname=db_xcpt',
'emulatePrepare' => true,
'username'=>'root',
'password'=>'root',
'charset' => 'utf8',
'tablePrefix' => 'xcpt_', //表前缀
),
array( //slave2
'connectionString'=>'mysql:host=localhost;dbname=db_xcpt',
'emulatePrepare' => true,
'username'=>'root',
'password'=>'root',
'charset' => 'utf8',
'tablePrefix' => 'xcpt_', //表前缀
),
),
),
希望本文所述对大家基于Yii框架的php程序设计有所帮助。
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
更新日志
- 陈洁仪.1994-心痛【立得唱片】【WAV+CUE】
- 车载必备专用超级选曲《劲爆中文DJ》2CD[WAV+CUE]
- 群星《民歌流淌60年(黑胶CD)》2CD[WAV+分轨]
- 群星《美丽时光》紫银合金AQCD[WAV+CUE]
- 群星《12大巨星畅销精选集》[WAV分轨][1.1G]
- 华语排行冠军曲《百事音乐风云榜》[WAV+CUE][1G]
- 奔驰汽车音乐圣经《醇声典范[白金嗓子] 男极声》音乐传真[WAV+CUE][1G]
- 陈影《如影随形HQ》头版限量[低速原抓WAV+CUE]
- 黄乙玲1996-心痛酒来洗[台湾首版][WAV+CUE]
- 曾庆瑜1990-随风而逝[日本东芝1A1首版][WAV+CUE]
- 群星.2015-凭着爱ADMS2CD【华纳】【WAV+CUE】
- 陈冠希.2017-一只猴子3部曲【摩登天空】【WAV+CUE】
- 金元萱.1996-迷迷糊糊【宝丽金】【WAV+CUE】
- 齐秦《燃烧爱情》马来西亚版[WAV+CUE][1G]
- 动力火车《结伴》2024最新 [FLAC分轨][1G]