首页 >后端开发 >php教程 >mysql主从数据库状态检测功能使用php如何实现?

mysql主从数据库状态检测功能使用php如何实现?

黄舟
黄舟原创
2017-07-20 13:41:351273浏览

这篇文章主要介绍了PHP实现的mysql主从数据库状态检测功能,结合具体实例形式分析了php检测多个mysql主从数据库连接状态的相关实现技巧,需要的朋友可以参考下

本文实例讲述了PHP实现的mysql主从数据库状态检测功能。分享给大家供大家参考,具体如下:

实例:


<?php
/**
 * 检测多个主从数据库是否挂掉
 * 建立从数据库$slave_db的二维数组,内容包含每个从服务器的配置数据
 */
header("Content-Type: text/html; charset=utf-8");
set_time_limit(0);
$slave_db = array(
  &#39;db1&#39;=>array(
    &#39;hostname&#39; => &#39;127.0.0.1&#39;,
    &#39;port&#39; => 3306,
    &#39;database&#39; => &#39;test&#39;,
    &#39;username&#39; => &#39;root&#39;,
    &#39;password&#39; => &#39;111111&#39;,
    &#39;charset&#39; => &#39;utf8&#39;,
  ),
  &#39;db2&#39;=>array(
    &#39;hostname&#39; => &#39;127.0.0.2&#39;,
    &#39;port&#39; => 3306,
    &#39;database&#39; => &#39;test&#39;,
    &#39;username&#39; => &#39;root&#39;,
    &#39;password&#39; => &#39;111111&#39;,
    &#39;charset&#39; => &#39;utf8&#39;,
  ),
);
$content = &#39;&#39;;
foreach ($slave_db as $db_key) {
  $host = $db_key[&#39;hostname&#39;];
  $port = $db_key[&#39;port&#39;];
  $db_user = $db_key[&#39;username&#39;];
  $db_pass = $db_key[&#39;password&#39;];
  $slave_link = mysql_connect($host,$db_user,$db_pass);
  if(mysql_errno()) {
    $content .= "从数据库( $host )无法连接 ! <br/>";
    $content .= mysql_error() . "<br/>";
    continue;
  }
  $sql = "show slave status";
  $result = mysql_query($sql, $slave_link);
  $row = mysql_fetch_assoc($result);
  $Slave_IO_Running = $row[&#39;Slave_IO_Running&#39;];
  $Slave_SQL_Running = $row[&#39;Slave_SQL_Running&#39;];
  if (&#39;Yes&#39; == $Slave_IO_Running && &#39;Yes&#39; == $Slave_SQL_Running) {
  } else {
    $content .= "从数据库( $host )挂掉了! <br/>";
  }
  mysql_free_result($result);
  mysql_close($slave_link);
}
//若报错信息不为空,发送报错邮件
if(!empty($content)) {
  $title = &#39;主从数据库状态检测报错 &#39;;
  $content = date("Y-m-d H:i:s",time()) . "<br/>" . $content;
  $sendurl = "http://localhost/api.ftrend.com/test.php?title=".$title."&content=".$content;
  $result = file_get_contents($sendurl);
  if(&#39;ok&#39; != $result) {
    $message = date("Y-m-d H:i:s",time()).&#39;slaveStatus.php主从数据库状态检测报错,邮件发送失败!&#39;."\n";
    $content = str_replace("<br/>", "\n", $content);
    $message .= $content;
    error_log($message,3,"error.log");
  }
}


<?php
$title = $_GET[&#39;title&#39;];
$content = $_GET[&#39;content&#39;];
$content = str_replace("<br/>", "\n", $content);
error_log($title."\n",3,&#39;error.log&#39;);
error_log($content."\n",3,&#39;error.log&#39;);
echo &#39;ok&#39;;

以上是mysql主从数据库状态检测功能使用php如何实现?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn