首頁 >後端開發 >php教程 >mysql主從資料庫狀態偵測功能使用php如何實作?

mysql主從資料庫狀態偵測功能使用php如何實作?

黄舟
黄舟原創
2017-07-20 13:41:351285瀏覽

這篇文章主要介紹了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