Home Backend Development PHP Tutorial php在linux下检测mysql同步状态的方法_php技巧

php在linux下检测mysql同步状态的方法_php技巧

May 16, 2016 pm 08:25 PM
linux mysql php method Detection

本文实例讲述了php在linux下检测mysql同步状态的方法。分享给大家供大家参考。具体分析如下:

这里通过两个实例来介绍mysql同步状态检测实现方法。代码如下:

复制代码 代码如下:
#!/bin/sh 
  
#check MySQL_Slave Status 
#crontab time 00:10 
MYSQL_USER="root"
MYSQL_PWD="123456"
MYSQL_SLAVE_LOG="/tmp/check_mysql_slave.log"
EMAIL="1351010****@139.com"
  
MYSQL_PORT=`netstat -na|grep "LISTEN"|grep "3306"|awk -F[:" "]+ '{print $5}'` 
MYSQL_IP=`ifconfig eth0|grep "inet addr" | awk -F[:" "]+ '{print $4}'` 
MYSQL_SLAVE_STATUS=$(/usr/local/webserver/mysql/bin/mysql -u root -psylc23hua -S /tmp/mysql.sock -e
 
"show slave statusG" | grep -i "running") 
IO_ENV=`echo $MYSQL_SLAVE_STATUS | grep IO | awk ' {print $2}'` 
SQL_ENV=`echo $MYSQL_SLAVE_STATUS | grep SQL | awk '{print $2}'` 
NOW=$(date -d today +'%Y-%m-%d %H:%M:%S') 
  
if [ "$MYSQL_PORT" = "3306" ];then
  echo "mysql is running!"
else
  mail -s "warn!server: $MYSQL_IP mysql is down" "$EMAIL"
fi
  
if [ "$IO_ENV" = "Yes" -a "$SQL_ENV" = "Yes" ];then
  echo "Slave is running!"
else
  echo "[ $NOW ] Slave is not running!" >> "$MYSQL_SLAVE_LOG"
  cat "$MYSQL_SLAVE_LOG" | mail -s "WARN! ${MySQL_IP}_replicate_error" "$EMAIL"
fi
  
exit 0

php实例代码,代码如下:
check_rep.php:
复制代码 代码如下:
if(emptyempty($_REQUEST["key"])) die(':) missing key');
if($_REQUEST["key"] != 'xupeng') die(':) error key');
 
include("mysql_instance.php");
include("check_status_api.php");
 
define("USERNAME", "用户名");
define("PASSWORD", "密码");
define("DEBUGMODE", false);
 
$instances = get_instances();
 
if($instances){
 echo  

 
END;
 echo "
n";
 if(!DEBUGMODE){
  echo "
n";
 }else{
  echo "
n";
 }
 foreach($instances as $host){
  $res = check_mysql_replication_status($host, USERNAME, PASSWORD);
  if(!DEBUGMODE){
   switch($res["result"]){
    case -4:
     $memo = "未知异常";
     break;
    case -3:
     $memo = "查询失败";
     break;
    case -2:
     $memo = "无法连接端口";
     break;
    case -1:
     $memo = "状态未知";
     break;
    case 0:
     $memo = "OK";
     break;
    case 1:
     $memo = "同步失败";
     if($res["Slave_IO_Running"] "Yes"){
      $memo .= $res["Last_IO_Error"] . "(" .  $res
 
["Last_IO_Errno"] . ")";
     }
     if($res["Slave_SQL_Running"] "Yes"){
      $memo .= $res["Last_SQL_Error"] . "(" .  $res
 
["Last_SQL_Errno"] . ")";
     }
     break;
    case 2:
     $memo = "数据库未设置同步";
     break;
   }
   echo "
 
n";
  }else{
   echo "
 
n";
  }
 }
 echo "



















































instance result Slave_IO_Running Slave_SQL_Running Master_Host Master_Port Replicate_Do_DB memo
instance result Slave_IO_Running Slave_SQL_Running Master_Host Master_Port Replicate_Do_DB Slave_IO_State Last_IO_Errno Last_IO_Error Last_SQL_Errno Last_SQL_Error
{$host} {$res['result']} {$res['Slave_IO_Running']} {$res['Slave_SQL_Running']} {$res['Master_Host']} {$res['Master_Port']} {$res['Replicate_Do_DB']} {$memo}
{$host} {$res['result']} {$res['Slave_IO_Running']} {$res['Slave_SQL_Running']} {$res['Master_Host']} {$res['Master_Port']} {$res['Replicate_Do_DB']} {$res['Slave_IO_State']} {$res['Last_IO_Errno']} {$res['Last_IO_Error']} {$res['Last_SQL_Errno']} {$res['Last_SQL_Error']}

n";
 echo  
END;
}else{
 die("no mysql instances defined.");
}

check_status_api.php:
复制代码 代码如下:
/*
 * 检查mysql服务器的同步状态
 */
function check_mysql_replication_status($host, $username, $password)
{
 //默认状态未知
 $r = array(
  "result" => -1
  );
 try{
  $dbh = @mysql_connect($host, $username, $password);
  if(!$dbh){
   //无法连接
   $r["result"] = -2;
   return($r);
  }
  $query = "SHOW SLAVE STATUS";
  $res = @mysql_query($query, $dbh);
  $err = @mysql_error();
  if($err){
   //无法连接
   $r["result"] = -3;
   return($r);
  }
  $row = mysql_fetch_array($res);
  $r = $row;
  if(($r["Slave_IO_Running"] == "Yes") && ($r["Slave_SQL_Running"] == "Yes"))
  {
   $r["result"] = 0;
  }else{
   if(!emptyempty($row)){
    $r["result"] = 1;
   }else{
    $r["result"] = 2;
   }
  }
 }catch(Exception $e){
  $r["result"] = -4;
 }
 return($r);
}

mysql_instance.php:
复制代码 代码如下:
//GRANT REPLICATION CLIENT ON *.* TO '用户名'@'监控主机ip' IDENTIFIED BY '密码';  $mysql_instances =
 
array(); 
$mysql_instances[] = "远程ip:端口"; 

function get_instances() 
{   
global $mysql_instances;   
return $mysql_instances;  
}


将以上三个PHP文件放在虚拟目录中,然后通过URL访问.

访问方式:http://ip/check_repl.php?key=xupeng

希望本文所述对大家的php程序设计有所帮助。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1242
24
How to understand DMA operations in C? How to understand DMA operations in C? Apr 28, 2025 pm 10:09 PM

DMA in C refers to DirectMemoryAccess, a direct memory access technology, allowing hardware devices to directly transmit data to memory without CPU intervention. 1) DMA operation is highly dependent on hardware devices and drivers, and the implementation method varies from system to system. 2) Direct access to memory may bring security risks, and the correctness and security of the code must be ensured. 3) DMA can improve performance, but improper use may lead to degradation of system performance. Through practice and learning, we can master the skills of using DMA and maximize its effectiveness in scenarios such as high-speed data transmission and real-time signal processing.

MySQL: The Database, phpMyAdmin: The Management Interface MySQL: The Database, phpMyAdmin: The Management Interface Apr 29, 2025 am 12:44 AM

MySQL and phpMyAdmin can be effectively managed through the following steps: 1. Create and delete database: Just click in phpMyAdmin to complete. 2. Manage tables: You can create tables, modify structures, and add indexes. 3. Data operation: Supports inserting, updating, deleting data and executing SQL queries. 4. Import and export data: Supports SQL, CSV, XML and other formats. 5. Optimization and monitoring: Use the OPTIMIZETABLE command to optimize tables and use query analyzers and monitoring tools to solve performance problems.

Composer: Aiding PHP Development Through AI Composer: Aiding PHP Development Through AI Apr 29, 2025 am 12:27 AM

AI can help optimize the use of Composer. Specific methods include: 1. Dependency management optimization: AI analyzes dependencies, recommends the best version combination, and reduces conflicts. 2. Automated code generation: AI generates composer.json files that conform to best practices. 3. Improve code quality: AI detects potential problems, provides optimization suggestions, and improves code quality. These methods are implemented through machine learning and natural language processing technologies to help developers improve efficiency and code quality.

How to uninstall MySQL and clean residual files How to uninstall MySQL and clean residual files Apr 29, 2025 pm 04:03 PM

To safely and thoroughly uninstall MySQL and clean all residual files, follow the following steps: 1. Stop MySQL service; 2. Uninstall MySQL packages; 3. Clean configuration files and data directories; 4. Verify that the uninstallation is thorough.

How to handle high DPI display in C? How to handle high DPI display in C? Apr 28, 2025 pm 09:57 PM

Handling high DPI display in C can be achieved through the following steps: 1) Understand DPI and scaling, use the operating system API to obtain DPI information and adjust the graphics output; 2) Handle cross-platform compatibility, use cross-platform graphics libraries such as SDL or Qt; 3) Perform performance optimization, improve performance through cache, hardware acceleration, and dynamic adjustment of the details level; 4) Solve common problems, such as blurred text and interface elements are too small, and solve by correctly applying DPI scaling.

An efficient way to batch insert data in MySQL An efficient way to batch insert data in MySQL Apr 29, 2025 pm 04:18 PM

Efficient methods for batch inserting data in MySQL include: 1. Using INSERTINTO...VALUES syntax, 2. Using LOADDATAINFILE command, 3. Using transaction processing, 4. Adjust batch size, 5. Disable indexing, 6. Using INSERTIGNORE or INSERT...ONDUPLICATEKEYUPDATE, these methods can significantly improve database operation efficiency.

Steps to add and delete fields to MySQL tables Steps to add and delete fields to MySQL tables Apr 29, 2025 pm 04:15 PM

In MySQL, add fields using ALTERTABLEtable_nameADDCOLUMNnew_columnVARCHAR(255)AFTERexisting_column, delete fields using ALTERTABLEtable_nameDROPCOLUMNcolumn_to_drop. When adding fields, you need to specify a location to optimize query performance and data structure; before deleting fields, you need to confirm that the operation is irreversible; modifying table structure using online DDL, backup data, test environment, and low-load time periods is performance optimization and best practice.

How to use MySQL functions for data processing and calculation How to use MySQL functions for data processing and calculation Apr 29, 2025 pm 04:21 PM

MySQL functions can be used for data processing and calculation. 1. Basic usage includes string processing, date calculation and mathematical operations. 2. Advanced usage involves combining multiple functions to implement complex operations. 3. Performance optimization requires avoiding the use of functions in the WHERE clause and using GROUPBY and temporary tables.

See all articles