在MySQL主從複製過程中,常常需要對某些重要的表進行一致性檢查。
由於主從資料在同步時存在一定的延遲,因此直接讀取伺服器資料的方式無法嚴格保證資訊的一致性。在資料在同步完全結束之前,一直處於不斷變化且並不完整的狀態下。鎖表的可能實現這個問題,但是效能又是需要考慮的。能對資料驗證是最好的。MySQL的CHECKSUM TABLE指令對於小型列表來說完全夠用,但規模龐大的列表往往需要“分塊”處理,避免在校正過程中造成負載過高。
Percona工具Pt-table-checksum 是不鎖表的。
基本文法:
Pt-table-checksum [options] [DSN]
舉例:
pt-table-checksum--databases=monster --tables=abc --replicate-checkh=192.168.1.186,u=chk,p=XXXX,P=3308
這個工具是通過在master上執行一些 checksum queries 主要是使用CRC32函數來實現 可以參考 --funcion 參數,這個是最易於計算的,來檢查主從複製的一致性,並將結果列印。如果主從資料不一樣的話,會產生不一樣的結果。
本欄目更多精彩內容:http://www.bianceng.cn/database/MySQL/
缺點:可能會增加伺服器負載。
--explain 選項的時候,可以查看到工具是如何校正資料表的。
該工具在master上執行一些 checksum queries ,然後會複製到slave上。
同一時間它只會在一個表上進行操作,所以不會在開始之前做大量的工作,也不許積累太多的記憶體。
它能夠在較大型的表上快速工作的原因是: it divides each table into chunks of rows。利用REPLACE..SELECT query來對每個chunk進行校正。而且它會動態調整chunk size(The tool keeps track of how quickly the server is able to execute the queries, and adjusts the chunks as it learns more about the server’s performance. 它使用一個指數衰減的加權平均保持穩定的塊大小)。這樣做避免了整個語句在表上運行一次。這樣可以降低主從複寫延遲的可能性。 在每個chunk上進行校正時,逾時時間為0.5S。
動態調整chunk size 的大小用到的是一種叫做:’ nibbling’的技術。它會優先利用主鍵或者非唯一主鍵來進行分塊或者其他的主鍵,如果沒有索引的話,而且表不是很大的話,表會被氛圍一個chunk。
該工具不會影響資料庫的任何操作,包括複製。(就是不鎖表的意思)pt-table-checksum detects replicas and connects to them automatically。當複寫延遲太多的時候,該工具會自動暫停,直到slave 與master同步。如果複製失敗的話,pt-table-checksum pauses and waits.並且不會有任何輸出。
工具在執行的時候,它會執行一個explain在每個chunk上,如果太大的話,它會跳過。可以通過 –chunk-size-limit 進行限制。 If a table will be checksummed in a single chunk because it has a small number of rows, pt-table-checksum additionally verifies that the table isn’t oversized on replicas 該工具會驗證在slave上這個表不會太大。這個可以避免在master 上表時空的,但是在slave上這個表很大。
有多種方式保證master負載不會太高。pt-table-checksum sets its session-level innodb_lock_wait_timeout to 1 second, so that if there is a lock wait, it will be the victim instead of causing other queries to time out. 。負載過大,他會pause。pt-table-checksum will pause if there are more than 25 concurrently executing queries. You should probably set a sane value for your server with the --max-load option
如果pt-table-checksum 意外停止 可以使用—resume 選項重啟。
Afterpt-table-checksumfinishes checksumming all of the chunks in a table, it pauses and waits for all detected replicas to finish executing the checksum queries. Once that is finished,it checks all of the replicas to see if they have the same data as the master, and then prints a line of output with the results.It will also print a progress report when it pauses to wait for replication to catch up, and when it is waiting to check replicas for differences from the master
如果使用 --replicate-check-only 這個選項的話,只有不同的檢測結果才會列印出來。