Codeigniter switch to secondary database if primar

2019-02-20 04:58发布

问题:

i'm wondering if there's a way to handle mysql error and configure ci to switch to a secondary DB server in the event the primary server is down (unable to connect) ?

回答1:

Well, I don't know if this is going to work, but you can actually try this:

1) create 2 groups of database settings (in application/config/database.php):

// regular one..
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
//...

// second connection
$db['second']['hostname'] = 'localhost';
$db['second']['username'] = 'root';
//...

2) Set deubg off to avoid showing db errors and actually killing your script (do it for both):

$db['default']['db_debug'] = FALSE;

3) You can pass a TRUE to the second paramenter while loading the library, so that it actually has a return value; it returns the database object itself:

$dbobject1 = $this->load->database('default',TRUE);
$dbobject2 = $this->load->database('second',TRUE);

Now, you can just check for the "connection ID" resource to see if a connection was established or not:

if(FALSE === $dbobject1->conn_id)
{
  echo 'No connection established!';
}

Now you can decide to load another DB in case the first doesn't load. The downside is, you don't know actually why the db connection didn't work, though...

As for how to implement this, you might want to try extending the database class or, better, create you own library which in fact just checks for whether a connection exists or not, and load this instead of the database library. Since it returns a database object (apart when all 2 connections fail), you can then work on that as you would do on the normal database class:

class Check_db {

     private $CI = '';
     public $DB1 = '';
     public $DB2 = '';

     function __construct()
     {
        $this->CI =&get_instance();
        $this->DB1 = $this->CI->load->database('default',TRUE);
        if(FALSE !== $this->DB1->conn_id)
        {
          return $this->DB1;
        }
        else
        {
          $this->DB2 = $this->CI->load->database('second',TRUE);
          if(FALSE !== $this->DB2->conn_id)
          {
            return $this->DB2;
          }
          else
          {
            return FALSE;
          }
        }
      }