Yii實(shí)現(xiàn)多數(shù)據(jù)庫(kù)主從讀寫分離的方法
本文實(shí)例講述了Yii實(shí)現(xiàn)多數(shù)據(jù)庫(kù)主從讀寫分離的方法。分享給大家供大家參考。具體分析如下:
Yii框架數(shù)據(jù)庫(kù)多數(shù)據(jù)庫(kù)、主從、讀寫分離 實(shí)現(xiàn),功能描述:
1.實(shí)現(xiàn)主從數(shù)據(jù)庫(kù)讀寫分離 主庫(kù):寫 從庫(kù)(可多個(gè)):讀
2.主數(shù)據(jù)庫(kù)無法連接時(shí) 可設(shè)置從數(shù)據(jù)庫(kù)是否 可寫
3.所有從數(shù)據(jù)庫(kù)無法連接時(shí) 可設(shè)置主數(shù)據(jù)庫(kù)是否 可讀
4.如果從數(shù)據(jù)庫(kù)連接失敗 可設(shè)置N秒內(nèi)不再連接
利用yii擴(kuò)展實(shí)現(xiàn),代碼如下:
/**
* 主數(shù)據(jù)庫(kù) 寫 從數(shù)據(jù)庫(kù)(可多個(gè))讀
* 實(shí)現(xiàn)主從數(shù)據(jù)庫(kù) 讀寫分離 主服務(wù)器無法連接 從服務(wù)器可切換寫功能
* 從務(wù)器無法連接 主服務(wù)器可切換讀功
* by lmt
* */
class DbConnectionMan extends CDbConnection {
public $timeout = 10; //連接超時(shí)時(shí)間
public $markDeadSeconds = 600; //如果從數(shù)據(jù)庫(kù)連接失敗 600秒內(nèi)不再連接
//用 cache 作為緩存全局標(biāo)記
public $cacheID = 'cache';
/**
* @var array $slaves.Slave database connection(Read) config array.
* 配置符合 CDbConnection.
* @example
* 'components'=>array(
* 'db'=>array(
* 'connectionString'=>'mysql://<master>',
* 'slaves'=>array(
* array('connectionString'=>'mysql://<slave01>'),
* array('connectionString'=>'mysql://<slave02>'),
* )
* )
* )
* */
public $slaves = array();
/**
*
* 從數(shù)據(jù)庫(kù)狀態(tài) false 則只用主數(shù)據(jù)庫(kù)
* @var bool $enableSlave
* */
public $enableSlave = true;
/**
* @var slavesWrite 緊急情況主數(shù)據(jù)庫(kù)無法連接 切換從服務(wù)器(讀寫).
*/
public $slavesWrite = false;
/**
* @var masterRead 緊急情況從主數(shù)據(jù)庫(kù)無法連接 切換從住服務(wù)器(讀寫).
*/
public $masterRead = false;
/**
* @var _slave
*/
private $_slave;
/**
* @var _disableWrite 從服務(wù)器(只讀).
*/
private $_disableWrite = true;
/**
*
* 重寫 createCommand 方法,1.開啟從庫(kù) 2.存在從庫(kù) 3.當(dāng)前不處于一個(gè)事務(wù)中 4.從庫(kù)讀數(shù)據(jù)
* @param string $sql
* @return CDbCommand
* */
public function createCommand($sql = null) {
if ($this->enableSlave && !emptyempty($this->slaves) && is_string($sql) && !$this->getCurrentTransaction() && self::isReadOperation($sql) && ($slave = $this->getSlave())
) {
return $slave->createCommand($sql);
} else {
if (!$this->masterRead) {
if ($this->_disableWrite && !self::isReadOperation($sql)) {
throw new CDbException("Master db server is not available now!Disallow write operation on slave server!");
}
}
return parent::createCommand($sql);
}
}
/**
* 獲得從服務(wù)器連接資源
* @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();
}
}
}
/**
* 檢測(cè)讀操作 sql 語(yǔ)句
*
* 關(guān)鍵字: 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;
}
/**
* 檢測(cè)從服務(wù)器是否被標(biāo)記 失敗.
*/
private function _isDeadServer($c) {
$cache = Yii::app()->{$this->cacheID};
if ($cache && $cache->get('DeadServer::' . $c) == 1) {
return true;
}
return false;
}
/**
* 標(biāo)記失敗的slaves.
*/
private function _markDeadServer($c) {
$cache = Yii::app()->{$this->cacheID};
if ($cache) {
$cache->set('DeadServer::' . $c, 1, $this->markDeadSeconds);
}
}
}
main.php配置:components 數(shù)組中,代碼如下:
'class'=>'application.extensions.DbConnectionMan',//擴(kuò)展路徑
'connectionString' => 'mysql:host=192.168.1.128;dbname=db_xcpt',//主數(shù)據(jù)庫(kù) 寫
'emulatePrepare' => true,
'username' => 'root',
'password' => 'root',
'charset' => 'utf8',
'tablePrefix' => 'xcpt_', //表前綴
'enableSlave'=>true,//從數(shù)據(jù)庫(kù)啟用
'urgencyWrite'=>true,//緊急情況 主數(shù)據(jù)庫(kù)無法連接 啟用從數(shù)據(jù)庫(kù) 寫功能
'masterRead'=>true,//緊急情況 從數(shù)據(jù)庫(kù)無法連接 啟用主數(shù)據(jù)庫(kù) 讀功能
'slaves'=>array(//從數(shù)據(jù)庫(kù)
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_', //表前綴
),
),
),
希望本文所述對(duì)大家基于Yii框架的php程序設(shè)計(jì)有所幫助。
- Yii操作數(shù)據(jù)庫(kù)的3種方法
- 解析yii數(shù)據(jù)庫(kù)的增刪查改
- PHP的Yii框架中使用數(shù)據(jù)庫(kù)的配置和SQL操作實(shí)例教程
- Yii2框架數(shù)據(jù)庫(kù)簡(jiǎn)單的增刪改查語(yǔ)法小結(jié)
- Yii2.0高級(jí)框架數(shù)據(jù)庫(kù)增刪改查的一些操作
- Yii2——使用數(shù)據(jù)庫(kù)操作匯總(增刪查改、事務(wù))
- YII2數(shù)據(jù)庫(kù)查詢實(shí)踐
- yii數(shù)據(jù)庫(kù)的查詢方法
- Yii2數(shù)據(jù)庫(kù)操作常用方法小結(jié)
- Yii操作數(shù)據(jù)庫(kù)實(shí)現(xiàn)動(dòng)態(tài)獲取表名的方法
- Yii 連接、修改 MySQL 數(shù)據(jù)庫(kù)及phpunit 測(cè)試連接
- Yii 框架使用數(shù)據(jù)庫(kù)(databases)的方法示例
相關(guān)文章
使用PHPExcel實(shí)現(xiàn)數(shù)據(jù)批量導(dǎo)出為excel表格的方法(必看)
下面小編就為大家?guī)硪黄褂肞HPExcel實(shí)現(xiàn)數(shù)據(jù)批量導(dǎo)出為excel表格的方法(必看)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-06-06關(guān)于Yii中模型場(chǎng)景的一些簡(jiǎn)單介紹
這篇文章主要給大家介紹了關(guān)于Yii中模型場(chǎng)景的一些簡(jiǎn)單介紹,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Yii具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09Laravel中重寫資源路由自定義URL的實(shí)現(xiàn)方法
這篇文章主要給大家介紹了關(guān)于Laravel中重寫資源路由自定義URL的實(shí)現(xiàn)方法,需要的朋友可以參考下2017-08-08Laravel 5.5官方推薦的Nginx配置學(xué)習(xí)教程
這篇文章主要給大家介紹了關(guān)于Laravel 5.5官方推薦的Nginx配置學(xué)習(xí)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2017-10-10基于OpenCart 開發(fā)支付寶,財(cái)付通,微信支付參數(shù)錯(cuò)誤問題
使用OpenCart 開發(fā)支付寶,財(cái)付通,微信支付如果稍不用心,很容易導(dǎo)致很多問題,而這些錯(cuò)誤很有可能是參數(shù)傳遞錯(cuò)誤,下面小編給大家整理了一篇文章很不錯(cuò),在此分享給大家,感興趣的朋友一起看看吧2015-10-10