mysql主从状态web监控

  • 通过在 MySQL 从库执行 show slave status; 可以获取主从同步的状态,根据这个思路,可以编写一个web页面,将同步状态作为页面的返回值添加到 zabbix 监控中,从而达到实时监控的目的。
同步状态 返回值
正常 {"Slave_Status":"UP","Seconds_Behind_Master":"延迟秒数"}
失败 {"Slave_Status":"Down","Seconds_Behind_Master":"NULL"}

php 语言

  • 可将下面的脚本保存为 mysql_slave_status.php
<?php
// 功能:检查从库同步状态

// MySQL从库配置
$db_config = [
    'host' => '192.168.31.103',
    'port' => 3306,
    'user' => 'dba_repl',
    'password' => 'MA6RuouuZZn4x_Hd',
    'dbname' => ''
];

// 设置响应格式:如果希望纯文本输出,改为'text/plain'
header('Content-Type: application/json; charset=utf-8');
error_reporting(0); // 直接关闭错误显示
ini_set('display_errors', 0);

$result = ['Slave_Status' => 'Down', 'Seconds_Behind_Master' => 'NULL'];
$connection = null;

try {
    // 创建MySQL连接
    $connection = @new mysqli(
        $db_config['host'],
        $db_config['user'],
        $db_config['password'],
        $db_config['dbname'],
        $db_config['port']
    );

    if ($connection->connect_error) {
        throw new Exception($connection->connect_error);
    }

    // 执行SHOW SLAVE STATUS查询
    $query_result = $connection->query("SHOW SLAVE STATUS");

    // 检查是否有从库状态记录
    if (!$query_result || $query_result->num_rows === 0) {
        throw new Exception('Not a slave');
    }

    // 获取从库状态
    $row = $query_result->fetch_assoc();
    $slave_io_running = $row['Slave_IO_Running'] ?? 'No';
    $slave_sql_running = $row['Slave_SQL_Running'] ?? 'No';
    $seconds_behind = $row['Seconds_Behind_Master'] ?? null;

    if ($slave_io_running === 'Yes' && $slave_sql_running === 'Yes') {
        $result['Slave_Status'] = 'UP';
        $result['Seconds_Behind_Master'] = (string)($seconds_behind ?? 0);
    }

    $query_result->free();

} catch (Exception $e) {
} finally {
    if ($connection && !$connection->connect_error) {
        $connection->close();
    }
}

echo json_encode($result, JSON_UNESCAPED_UNICODE);

效果展示

  • 场景1:MySQL 从库同步正常、延迟1秒的状态

  • 场景2:MySQL 从库同步失败的状态

Copyright © www.sqlfans.cn 2021 - 2026 All Right Reserved更新时间: 2026-04-30 09:56:43

results matching ""

    No results matching ""