mysqldump備份時導致所有數據表鎖定,無法提供服務

背景

有接到用戶反饋:系統頁面卡住不動。。

這個問題發生在生產環境下數據庫的每日備份過程中,一個20+G的數據庫,在定時備份時(關於如何配置線上數據庫定時備份,可參考文章:Ubuntu下對MySQL指定數據庫定時備份)導致數據庫卡死,持續時長5分鐘左右,在此期間線上服務無響應。。

分析

備份一個庫:mysqldump -hhost -uroot -ppassword dbname > /opt/backup.sql

直接使用上述語句備份數據庫,存在的問題是:備份完成之前,會把所有的表鎖住,導致無法寫入。。

這在生產環境下是不可接受的,而且這才20+G,後續數據庫Size會越來越大,備份的時間必然也越長。。

那麼,有沒有一種方法在完成備份的同時並不鎖定表呢??往下看。

解決

在使用mysqldump備份時,加一個參數:--single-transaction,這樣,便可以在備份庫的時候並不鎖定數據表。

mysqldump -hhost -uroot -ppassword --single-transaction dbname > /opt/backup.sql

原理說明:

Some internals on how this actually works - before the utility starts fetching data from the server, it sends it a START TRANSACTION command. This command serves few goals in this case. The first one, is to have a consistent backup created, from a specific point in time, regardless of changes that occur after the backup started. The second goal is to prevent those locks from happening, as we are performing our actions as part of a database transaction.

Notes: 僅對支持事務的表有效,比如InnoDB,對非事務型的表比如MyISAM`則沒有效果。

另外需要注意的是,當使用--single-transaction這個參數備份大型數據庫時,可考慮和--quick參數結合使用。--quick可以讓mysqldump在備份的過程中每次只取一行數據,而不是把所有行都緩存到內存裏,這主要考慮了服務器內存限制,以防備份失敗。

mysqldump -hhost -uroot -ppassword --single-transaction --quick dbname > /opt/backup.sql

這樣,在備份時並不會對數據表加鎖,線上業務完全不受影響,經測試,備份耗時基本不變。

Reference: How to backup MySQL database using Mysqldump without locking?


If you have any questions or any bugs are found, please feel free to contact me.

Your comments and suggestions are welcome!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章