0
votes

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;
}   
1
More than worrying about the retry logic, you might first want to focus on figuring out why those errors are occurring in the first place, why is the database connection timing out so often - Hanky Panky
@Hanky웃Panky These errors are bound to happen not because something's wrong with the code but because of the shared infrastructure. These are transient errors and the application should be architected to deal with these errors gracefully. - Gaurav Mantri

1 Answers

0
votes

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)