日度归档:2017年3月16日

用php监控从库同步延迟个数

<?php
$mysqli = new mysqli('slave_host', 'root', 'passwd', 'dbname');

/*
 * This is the "official" OO way to do it,
 * BUT $connect_error was broken until PHP 5.2.9 and 5.3.0.
 */
if ($mysqli->connect_error) {
 die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}

/*
 * Use this instead of $connect_error if you need to ensure
 * compatibility with PHP versions prior to 5.2.9 and 5.3.0.
 */
if (mysqli_connect_error()) {
 die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
}

echo 'Success... ' . $mysqli->host_info . "\n";

/* Create table doesn't return a resultset */
/**
 * 
 * @var mysqli_result $result
 */
$result = $mysqli->query("show slave status");

if ($mysqli->errno) {
 printf("Error number: %s\n", $mysqli->errno);
 printf("Error message: %s\n", $mysqli->error);
}

if ($result !== false) {
 $row = $result->fetch_assoc();
 echo "master : {$row['Master_Log_File']}\n";
 echo "slave relay : {$row['Relay_Master_Log_File']}\n";
 echo " : " . ($row['Read_Master_Log_Pos'] - $row['Exec_Master_Log_Pos']);
}

$mysqli->close();