mysqldump 利用rr隔离实现一致性备份

mysqldump -p -S /data/mysqldata1/sock/mysql.sock --single-transaction  --master-data=2  --database db1 db2 db3 > db.sql
1、single-transaction
官方解释如下:
--single-transaction:
     Creates a consistent snapshot by dumping all tables in a single transaction. Works ONLY for tables stored in storage engines which support multiversioning (currently  only InnoDB does); the dump is NOT guaranteed to be consistent for other storage engines. While a --single-transaction dump is in process, to ensure avalid dump file (correct table contents and binary log position), no other connection should use the following statements:ALTER TABLE, DROP TABLE, RENAME TABLE, TRUNCATE TABLE, as consistent snapshot is not isolated from them. Option automatically turns off --lock-tables.   

由上面加粗的黑体字可以看到几个关键信息:
    (1)可以在一个事务里对全部表获取一个一致性快照这里保证了可以在此时获得此一时刻的一致性数据;
    (2)只对有版本控制的存储引擎,目前为止是只有innodb有这个功能同样大众的myisam引擎使用不了;
    (3)在这个过程中,alter、drop、rename和truncate是无法隔离的,即不能使用额表操作
    (4)自动关闭 --lock-tables 选项
    
    我们打开mysql的general-log,来查看 mysqldump --single-transaction -B test >t.log到底发生了什么,查看general-log,如下:
    (1) SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ
    (2)START TRANSACTION /*!40100 WITH CONSISTENT SNAPSHOT */
    (3)UNLOCK TABLES
    第一行是使当前session的事务级别为可重复读;
    第二行是开始一个事务并且获得一个一致性快照,其实这个时候就是对当前所有表的数据进行了一个保存,其实这里应该使用了MVCC多版本控制,这就是为什么只有innodb才有的功能;
    第三行是释放锁,这也解释了为什么说使用mysqldump不会锁表(因为第二行已经取得了快照,不需要锁表了)。


为什么需要RR隔离?

这样一个session 看到的都是一个时间点的数据

原文地址:https://www.cnblogs.com/zhaoyangjian724/p/6199409.html