MysqL 的逻辑恢复
1. 完全恢复
MysqL 中,逻辑备份的完全恢复相对比较简单,一般包含两个步骤:
- 恢复最新的全备文件
- 恢复日志文件
实际案例:完整的MysqLdump备份与恢复
1. 中午12点,备份数据库
[MysqL@localhost ~]$ MysqLdump --single-transaction -F -uroot -p --databases tempdb > /tmp/db_tempdb.sql
Enter password:
[MysqL@localhost ~]$ ls -lrt db_tempdb.sql
-rw-r--r-- 1 MysqL MysqL 19602842 Jul 23 12:01 db_tempdb.sql
参数 --single-transaction 表示给 InnoDB 表生成快照,保持数据一致性
此时表 customer 的数据如下:
MysqL> select * from customer;
+----+-----------+------------+------------+--------+---------+
| id | last_name | first_name | birth_date | gender | balance |
+----+-----------+------------+------------+--------+---------+
| | | | -- | | |
| | | | -- | | |
+----+-----------+------------+------------+--------+---------+
rows in set ( sec)
2. 13点,表 customer 插入新的数据:
MysqL> insert into customer(id,last_name,first_name,birth_date,gender,balance) values(,,,'2020-08-10',,);
Query OK, row affected ( sec)
MysqL> insert into customer(id,last_name,first_name,birth_date,gender,balance) values(,,,'2020-09-10',,);
Query OK, row affected ( sec)
3. 14点,数据库故障,需要恢复数据:
恢复后表 customer 的数据如下:
MysqL> select * from customer;
+----+-----------+------------+------------+--------+---------+
| id | last_name | first_name | birth_date | gender | balance |
+----+-----------+------------+------------+--------+---------+
| | | | -- | | |
| | | | -- | | |
+----+-----------+------------+------------+--------+---------+
rows in set ( sec)
恢复日志后,表 customer 的数据如下:
MysqL> select * from customer;
+----+-----------+------------+------------+--------+---------+
| id | last_name | first_name | birth_date | gender | balance |
+----+-----------+------------+------------+--------+---------+
| | | | -- | | |
| | | | -- | | |
| | | | -- | | |
| | | | -- | | |
+----+-----------+------------+------------+--------+---------+
rows in set ( sec)
表 customer 的数据全部恢复。
2. 不完全恢复
MysqL 中,不完全恢复分为基于时间点的恢复和基于位置的恢复。一般来说,不完全恢复需要跳过一些语句,比如说,由于误操作删除了一张表,这时用完全恢复是没有用的,因为 binlog 日志还存在误操作的语句,我们需要跳过误操作语句,在恢复后面的语句,来完成恢复。
2.1 基于时间点恢复
以下是基于时间点恢复的操作步骤:
[MysqL@localhost ~]$ MysqL -uroot -p tempdb < /tmp/db_tempdb.sql
Enter password:
[MysqL@localhost ~]$ MysqLbinlog --stop-datetime="2020-07-23 11:59:59" MysqL-bin.000021 | MysqL -uroot -p tempdb
Enter password:
2. 跳过故障时间点,继续使用后面的binlog日志完成恢复。
[MysqL@localhost ~]$ MysqLbinlog --start-datetime="2020-07-23 12:01:00" MysqL-bin.000021 | MysqL -uroot -p tempdb
Enter password:
2.2 基于位置恢复
以下是基于位置恢复的操作步骤:
[MysqL@localhost ~]$ MysqLbinlog --start-datetime="2020-07-23 11:55:00" --stop-datetime="2020-07-23 12:05:00" MysqL-bin.000021 > /tmp/temp_restore.sql
从 temp_restore.sql 找到误操作语句前后的位置号为 383 和 437:
[MysqL@localhost ~]$ MysqL -uroot -p tempdb < /tmp/db_tempdb.sql
Enter password:
[MysqL@localhost ~]$ MysqLbinlog --stop-position="383" MysqL-bin.000021 | MysqL -uroot -p tempdb
Enter password:
[MysqL@localhost ~]$ MysqLbinlog --start-position="437" MysqL-bin.000021 | MysqL -uroot -p tempdb
Enter password: