Yii實現多資料庫主從讀寫分離的方法_php執行個體

來源:互聯網
上載者:User

本文執行個體講述了Yii實現多資料庫主從讀寫分離的方法。分享給大家供大家參考。具體分析如下:

Yii架構資料庫多資料庫、主從、讀寫分離 實現,功能描述:

1.實現主從資料庫讀寫分離 主庫:寫 從庫(可多個):讀

2.主要資料庫無法串連時 可設定從資料庫是否 可寫

3.所有從資料庫無法串連時 可設定主要資料庫是否 可讀

4.如果從資料庫連接失敗 可設定N秒內不再串連

利用yii擴充實現,代碼如下:

複製代碼 代碼如下:
<?php
/**
 * 主要資料庫 寫 從資料庫(可多個)讀
 * 實現主從資料庫 讀寫分離 主伺服器無法串連 從伺服器可切換寫功能
 * 從務器無法串連 主伺服器可切換讀功
 * by lmt
 * */
class DbConnectionMan extends CDbConnection {
    public $timeout = 10; //連線逾時時間
    public $markDeadSeconds = 600; //如果從資料庫連接失敗 600秒內不再串連 
    //用 cache 作為緩衝全域標記
    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();
    /**
     * 
     * 從資料庫狀態 false 則只用主要資料庫
     * @var bool $enableSlave
     * */
    public $enableSlave = true;
 
    /**
     * @var slavesWrite 緊急情況主要資料庫無法串連 切換從伺服器(讀寫).
     */
    public $slavesWrite = false;
 
    /**
     * @var masterRead 緊急情況從主要資料庫無法串連 切換從住伺服器(讀寫).
     */
    public $masterRead = false;
 
    /**
     * @var _slave
     */
    private $_slave;
 
    /**
     * @var _disableWrite 從伺服器(唯讀).
     */
    private $_disableWrite = true;
 
    /**
     *
     * 重寫 createCommand 方法,1.開啟從庫 2.存在從庫 3.當前不處於一個事務中 4.從庫讀資料
     * @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);
        }
    }
 
    /**
     * 獲得從伺服器串連資源
     * @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程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.