Step 4: Modify your database connection program
Now that you have established a mutual relationship between machine A and machine B, you need to modify your database connection program to benefit from this approach. The following function first attempts to connect to machine A, and if the connection cannot be established, connects to machine B.
$#@60;?php
/********************************************************
function db_connect()
returns a link identifier on success, or false on error
********************************************************/
function db_connect(){
$username = "replUser";
$password = "password";
$primary = "10.1.1.1";
$backup = "10.1.1.2";
# attempt connection to primary
if(!$link_id = @mysql_connect($primary, $username, $ password))
# attempt connection to secondary
$link_id = @mysql_connect($secondary, $username, $password)
return $link_id;
}
?$#@62;
I tested the database connection establishment process using the above technology in two situations. One is that the main MySQL service program is shut down, but the server is still running. The other is that the main server is shut down. If only mysqld is shut down, the connection will be immediately transferred to the backup machine; but if the entire server is shut down, there will be an infinite wait (I gave up tracking after two minutes - a very short attention span) because PHP is looking for a server that does not exist. server. Unfortunately, unlike the fsockopen function, the mysql_connect function does not have a timeout parameter, however we can use fsockopen to simulate a timeout.