最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Yii實現(xiàn)多數(shù)據庫主從讀寫分離的方法

 更新時間:2014年12月29日 10:48:30   投稿:shichen2014  
這篇文章主要介紹了Yii實現(xiàn)多數(shù)據庫主從讀寫分離的方法,通過針對Yii數(shù)據庫類的擴展實現(xiàn)多數(shù)據庫主從讀寫的分離功能,是非常實用的技巧,需要的朋友可以參考下

本文實例講述了Yii實現(xiàn)多數(shù)據庫主從讀寫分離的方法。分享給大家供大家參考。具體分析如下:

Yii框架數(shù)據庫多數(shù)據庫、主從、讀寫分離 實現(xiàn),功能描述:

1.實現(xiàn)主從數(shù)據庫讀寫分離 主庫:寫 從庫(可多個):讀

2.主數(shù)據庫無法連接時 可設置從數(shù)據庫是否 可寫

3.所有從數(shù)據庫無法連接時 可設置主數(shù)據庫是否 可讀

4.如果從數(shù)據庫連接失敗 可設置N秒內不再連接

利用yii擴展實現(xiàn),代碼如下:

復制代碼 代碼如下:
<?php
/**
 * 主數(shù)據庫 寫 從數(shù)據庫(可多個)讀
 * 實現(xiàn)主從數(shù)據庫 讀寫分離 主服務器無法連接 從服務器可切換寫功能
 * 從務器無法連接 主服務器可切換讀功
 * by lmt
 * */
class DbConnectionMan extends CDbConnection {
    public $timeout = 10; //連接超時時間
    public $markDeadSeconds = 600; //如果從數(shù)據庫連接失敗 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();
    /**
     * 
     * 從數(shù)據庫狀態(tài) false 則只用主數(shù)據庫
     * @var bool $enableSlave
     * */
    public $enableSlave = true;
 
    /**
     * @var slavesWrite 緊急情況主數(shù)據庫無法連接 切換從服務器(讀寫).
     */
    public $slavesWrite = false;
 
    /**
     * @var masterRead 緊急情況從主數(shù)據庫無法連接 切換從住服務器(讀寫).
     */
    public $masterRead = false;
 
    /**
     * @var _slave
     */
    private $_slave;
 
    /**
     * @var _disableWrite 從服務器(只讀).
     */
    private $_disableWrite = true;
 
    /**
     *
     * 重寫 createCommand 方法,1.開啟從庫 2.存在從庫 3.當前不處于一個事務中 4.從庫讀數(shù)據
     * @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 數(shù)組中,代碼如下:
復制代碼 代碼如下:
'db'=>array(
        'class'=>'application.extensions.DbConnectionMan',//擴展路徑
        'connectionString' => 'mysql:host=192.168.1.128;dbname=db_xcpt',//主數(shù)據庫 寫
        'emulatePrepare' => true,
        'username' => 'root',
        'password' => 'root',
        'charset' => 'utf8',
        'tablePrefix' => 'xcpt_', //表前綴
        'enableSlave'=>true,//從數(shù)據庫啟用
   'urgencyWrite'=>true,//緊急情況 主數(shù)據庫無法連接 啟用從數(shù)據庫 寫功能
    'masterRead'=>true,//緊急情況 從數(shù)據庫無法連接 啟用主數(shù)據庫 讀功能
        'slaves'=>array(//從數(shù)據庫
            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程序設計有所幫助。

相關文章

  • 記Laravel調用Gin接口調用formData上傳文件的實現(xiàn)方法

    記Laravel調用Gin接口調用formData上傳文件的實現(xiàn)方法

    這篇文章主要介紹了記Laravel調用Gin接口調用formData上傳文件的實現(xiàn)方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-12-12
  • 寶塔 php修改了php.ini配置不生效的問題及解決方法

    寶塔 php修改了php.ini配置不生效的問題及解決方法

    最近在使用hypref,php的版本是7.4,服務器linux,用寶塔安裝完php,并裝完swoole插件后,安裝了swoole后,需要在php.ini中修改一下配置文件,本文給大家分享寶塔 php修改了php.ini配置不生效的問題及解決方法,感興趣的朋友一起看看吧
    2023-09-09
  • smarty內置函數(shù)capture用法分析

    smarty內置函數(shù)capture用法分析

    這篇文章主要介紹了smarty內置函數(shù)capture用法,實例分析了capture的三種常見用法,需要的朋友可以參考下
    2015-01-01
  • Laravel框架驗證碼類用法實例分析

    Laravel框架驗證碼類用法實例分析

    這篇文章主要介紹了Laravel框架驗證碼類用法,結合實例形式分析了Laravel框架驗證碼類的使用操作技巧與相關注意事項,需要的朋友可以參考下
    2019-09-09
  • PHPExcel 修改已存在Excel的方法

    PHPExcel 修改已存在Excel的方法

    下面小編就為大家分享一篇PHPExcel 修改已存在Excel的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-05-05
  • thinkphp連貫操作實例分析

    thinkphp連貫操作實例分析

    這篇文章主要介紹了thinkphp連貫操作,以實例形式較為詳細的分析了連貫操作的具體用法及常用的方法含義,是非常實用的技巧,需要的朋友可以參考下
    2014-11-11
  • 純PHP代碼實現(xiàn)支付寶批量付款

    純PHP代碼實現(xiàn)支付寶批量付款

    最近在做一個使用支付寶轉賬的項目,其中有需求把我難到了:批量支付成功后不知道怎么接收系統(tǒng)返回的通知,經過朋友幫忙,此功能實現(xiàn),下面小編把具體代碼整理分享給大家,供大家參考
    2015-12-12
  • 發(fā)款php蜘蛛統(tǒng)計插件只要有mysql就可用

    發(fā)款php蜘蛛統(tǒng)計插件只要有mysql就可用

    有時候我們?yōu)榱丝匆幌轮┲肱佬械那闆r,不得不對日志進行大量的分析,由此想做一款插件可以記錄蜘蛛的情況。在第一次做的時候,只是記錄下蜘蛛的爬行次數(shù),不大好分析。
    2010-10-10
  • PHP刪除數(shù)組中指定下標的元素方法

    PHP刪除數(shù)組中指定下標的元素方法

    下面小編就為大家分享一篇PHP刪除數(shù)組中指定下標的元素方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-02-02
  • Smarty變量用法詳解

    Smarty變量用法詳解

    這篇文章主要介紹了Smarty變量用法,結合實例形式分析了php分配變量與配置文件讀取變量的具體使用方法,需要的朋友可以參考下
    2016-05-05

最新評論

桂林市| 西藏| 滕州市| 栾城县| 连平县| 绥化市| 龙陵县| 亳州市| 南充市| 阿克陶县| 商洛市| 福清市| 锦屏县| 南昌县| 鹤庆县| 满洲里市| 威远县| 凤翔县| 嵊州市| 定远县| 嵊泗县| 建瓯市| 海城市| 龙胜| 宕昌县| 泽库县| 定陶县| 秦安县| 阿克苏市| 馆陶县| 大埔区| 兰溪市| 喀什市| 孝感市| 资源县| 通海县| 石阡县| 林甸县| 黄陵县| 夏河县| 莫力|