針對主機 A (動態 IP) → 主機 B (固定 IP) 的單向資料同步需求,採用 PHP 腳本比對最大 ID 差異並補寫,配合 Crontab 定時執行。
$local_max_id)。$remote_max_id)。$local_max_id > $remote_max_id,查出差異區間資料 LIMIT $remote_max_id, $diff。INSERT 寫入主機 B。<?php
$local = mysqli_connect('localhost', 'user', 'pass', 'test');
$remote = mysqli_connect('5.6.7.8', 'user', 'pass', 'test');
$local_max = (int)mysqli_fetch_row(mysqli_query($local, 'SELECT MAX(id) FROM t'))[0];
$remote_max = (int)mysqli_fetch_row(mysqli_query($remote, 'SELECT MAX(id) FROM t'))[0];
if ($local_max > $remote_max) {
$res = mysqli_query($local, "SELECT col FROM t WHERE id > $remote_max AND id <= $local_max");
while ($row = mysqli_fetch_row($res)) {
mysqli_query($remote, "INSERT INTO t(col) VALUES('".mysqli_real_escape_string($remote, $row[0])."')");
}
}
mysqli_close($local); mysqli_close($remote);
?>
# /etc/crontab
0 2 * * * root /usr/bin/php -q /home/sync/sync_t.php >> /var/log/sync_t.log 2>&1
每天凌晨 2 點自動執行,日誌留存備查。
INSERT ... VALUES (...),(...) 或 LOAD DATA 提升效能。