dongyuan7981 2014-04-30 06:21
浏览 159

PHP MySQL连接错误 - 实现重试逻辑

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条回答 默认 最新

  • duanmao9918 2014-04-30 06:55
    关注

    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)

    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算