Reputation: 362
We are seeing lot of PHP and MYSQL Connection failure issues. It has been suggested that we shall built the retry logic, if the database connection is not successful. I have pasted below the code and the error message.
Can anybody advise what shall be the best way to implement the retry logic in this code? Any code sample which handles this?
PHP Warning: mysqli_connect(): [2002] A connection attempt failed because the connected party did not properly respond after a period of time, or established connecti (trying to connect via tcp://us-cdbr-azure-west-a.cloudapp.net:3306) in D:\home\site\wwwroot\xdfdy.php on line 232
PHP Warning: mysqli_connect(): (HY000/2002): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
public function connect_to_mysqldb () {
try
{
$this->conn = mysqli_connect('us-cdbr-azure-west-a.cloudapp.net','xxxxx','password', 'dbname');
}
catch (DbException $e) {
return false;
}
// Check connection
if (mysqli_connect_errno($this->conn ))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return false;
}
return true;
}
Upvotes: 0
Views: 2187
Reputation: 7034
If following the people that already invented the wheel, which say every unnecessary attempt to DB connection might run into performance issues, and also one of the reasons that they suggest you only need one instance of the database, I would tell you DO NOT DO IT, but however, the question is asked.
Although, I have never done this before, it seems for me like you can call your function recursively until establishing a connection
public function connect_to_mysqldb () {
try
{
$this->conn = mysqli_connect('us-cdbr-azure-west-a.cloudapp.net','xxxxx','password', 'dbname');
}
catch (DbException $e) {
// write into logs maybe?
$this->connect_to_mysqldb();
}
// Check connection (maybe unreachable because of the catch block?)
if (mysqli_connect_errno($this->conn ))
{
$this->connect_to_mysqldb();
}
return true;
}
So, while your connection has errors, the method will call itself and will return (true) only when the catch
and the if
blocks are skipped (the connection is established)
Upvotes: 0