【问题标题】:Yii Database Failover Fail OverYii 数据库故障转移故障转移
【发布时间】:2015-01-14 18:14:40
【问题描述】:

我目前正在做一个项目,我们选择 Yii 作为我们选择的新框架。我目前正在尝试找出在 Yii 中实现某种自动数据库故障转移的最佳方法。

我目前正在尝试覆盖 CDbConnection 类 - 打开功能。我不确定我是否朝着正确的方向前进。

基本上我要做的是检查一个数据库连接,如果它失败连接到另一个数据库。简单的概念我只是不知道把它放在哪里。我知道使用 mysqlnd_ms 有更好的方法来做到这一点,但它还没有在我们正在使用的服务器上设置,所以必须想出一种在 Yii 中做到这一点的方法。任何帮助是极大的赞赏。 -DA

这就是我目前的想法?

class DaDbConnection extends CDbConnection{

public $dbConnectTries = 6;
public $numDatabases = 3;
private $_tries =0;
private $_db = 1;

/*
 * Extends CDbConnection open() method
 * Tries to connect to database connections setup in config/main.php up to 
 * the value of $dbConnectionTries or a connection is successful
 * @throws CException If it can not connect to any DBs
 */
protected function open()
{
    try{
        //try to connect to the default DB
        parent::open();

    }catch(Exception $e){
        if($this->_tries < $this->dbConnectTries){

            //If there aren't anymore DBs to try we must start over from the first
            if($this->_db >= $this->numDatabases){
                $tryDb = 'db';
                $this->_db = 0;
            }else{
               $tryDb = 'db'.$this->_db;
            }

            $this->_db++;
            $this->_tries++;

            $this->connectionString = Yii::app()->$tryDb->connectionString;
            $this->username = Yii::app()->$tryDb->username;
            $this->password = Yii::app()->$tryDb->password;
            $this->open();
        }else{
            throw new CDbException('Could Not Connect to a DB.');
        }
    }    
}

}

【问题讨论】:

    标签: database yii failover


    【解决方案1】:

    听起来方向是正确的。我不确定 Yii 有什么内置的,如果我错了,请有人纠正我。

    我可能会尝试在我的主配置文件中定义两个数据库,但使用我自己的自定义类;

    return array(
        ...
        'components' => array(
            'db' => array(
                'connectionString' => 'mysql:host=dbserver1;dbname=my1db',
                ...
                'class'            => 'MyCDbConnection',
                ...
            ),
            'dbBackup' => array(
                'connectionString' => 'mysql:host=dbserver2;dbname=my2db',
                ...
                'class'            => 'MyCDbConnection',
            ),
            ...
        ),
    );
    

    然后,我会按照您的建议让 MyCDbConnection 类扩展主 CDbConnection 类,但包含我自己的 open 方法。

    可以很容易地在数据库之间切换(例如Multiple-database support in Yii),我相信您可以将其集成到自定义open() 方法中打开数据库连接的try/catch 中?

    【讨论】:

    • 为了完整起见,您需要覆盖getDbConnection()
    • 我在上面添加了我的代码,我只是在 CDbConnection 无法连接时切换它使用的连接字符串。
    猜你喜欢
    • 2010-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-17
    • 2018-03-15
    • 2012-07-04
    • 2012-07-13
    相关资源
    最近更新 更多