我目前正在做一个项目,我们选择了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.');
}
}
}}
发布于 2012-12-22 00:56:02
听起来像是正确的方向。我不确定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中。
https://stackoverflow.com/questions/13993927
复制相似问题