可以看到 --lock-tables 在导出一个数据库时,会在整个导出过程 lock read local 所有的表。该锁不会阻止其它session读和插入。
2)--lock-all-tables 的实现:
先执行:mysqldump -uroot -p --databases gs --lock-all-tables > gs_l.sql, 在查看 general.log:
151022 14:34:13 4 Connect root@localhost on 4 Query /*!40100 SET @@SQL_MODE='' */ 4 Query /*!40103 SET TIME_ZONE='+00:00' */ 4 Query FLUSH TABLES 4 Query FLUSH TABLES WITH READ LOCK 4 Query SHOW VARIABLES LIKE 'gtid\_mode' ... ... 4 Init DB gs 4 Query SHOW CREATE DATABASE IF NOT EXISTS `gs` 4 Query show tables ... ...4 Query SELECT /*!40001 SQL_NO_CACHE */ * FROM `tb1` 4 Query SET SESSION character_set_results = 'binary' 4 Query use `gs` 4 Query select @@collation_database ... ... 4 Query show fields from `user` 4 Query SELECT /*!40001 SQL_NO_CACHE */ * FROM `user` 4 Query SET SESSION character_set_results = 'binary' 4 Query use `gs` 4 Query select @@collation_database 4 Query SHOW TRIGGERS LIKE 'user' 4 Query SET SESSION character_set_results = 'utf8' 4 Quit
它的实现使用了 FLUSH TABLES; FLUSH TABLES WITH READ LOCK; 语句。在最后没有看到解锁语句。
它请求发起一个全局的读锁,会阻止对所有表的写入操作,以此来确保数据的一致性。备份完成后,该会话断开,会自动解锁。
3)--single-transaction 的实现:
先执行: mysqldump -uroot -p --databases gs --single-transaction > gs_l.sql,在查看 general.log:
151022 14:41:34 5 Connect root@localhost on 5 Query /*!40100 SET @@SQL_MODE='' */ 5 Query /*!40103 SET TIME_ZONE='+00:00' */ 5 Query SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ 5 Query START TRANSACTION /*!40100 WITH CONSISTENT SNAPSHOT */ 5 Query SHOW VARIABLES LIKE 'gtid\_mode' 5 Query UNLOCK TABLES ... ... 5 Init DB gs 5 Query SHOW CREATE DATABASE IF NOT EXISTS `gs` 5 Query SAVEPOINT sp ...... 5 Query show create table `tb1` ......5 Query SELECT /*!40001 SQL_NO_CACHE */ * FROM `tb1` ...... 5 Query ROLLBACK TO SAVEPOINT sp ...... 5 Query show create table `user` .....5 Query SELECT /*!40001 SQL_NO_CACHE */ * FROM `user` ...... 5 Query ROLLBACK TO SAVEPOINT sp 5 Query RELEASE SAVEPOINT sp 5 Quit
基本过程是:
1> 先改变事务隔离级别:SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ
2> 开始事务:START TRANSACTION /*!40100 WITH CONSISTENT SNAPSHOT */
3> unlock tables;
4> 导出建库语句; SHOW CREATE DATABASE IF NOT EXISTS `gs`
5> 打开一个 savepoint: SAVEPOINT sp;
6> 导出 表 tb1 的结构和数据;
7> ROLLBACK TO SAVEPOINT sp; 回滚到savepoint;
对其它表重复该过程;
8> 最后 realease savepoint p; 释放savepoint;