http://blog.itpub.net/22664653/viewspace-1140915/
介紹double write之前我們有必要了解partial page write 問題 :
InnoDB 的Page Size一般是16KB,其資料校驗也是針對這16KB來計算的,将資料寫入到磁盤是以Page為機關進行操作的。而計算機硬體和作業系統,在極端情況下(比如斷電)往往并不能保證這一操作的原子性,16K的資料,寫入4K 時,發生了系統斷電/os crash ,隻有一部分寫是成功的,這種情況下就是 partial page write 問題。
很多DBA 會想到系統恢複後,MySQL 可以根據redolog 進行恢複,而mysql在恢複的過程中是檢查page的checksum,checksum就是pgae的最後事務号,發生partial page write 問題時,page已經損壞,找不到該page中的事務号,就無法恢複。
一 double write是什麼?
Double write 是InnoDB在 tablespace上的128個頁(2個區)是2MB;
其原理:
為了解決 partial page write 問題 ,當mysql将髒資料flush到data file的時候, 先使用memcopy 将髒資料複制到記憶體中的double write buffer ,之後通過double write buffer再分2次,每次寫入1MB到共享表空間,然後馬上調用fsync函數,同步到磁盤上,避免緩沖帶來的問題,在這個過程中,doublewrite是順序寫,開銷并不大,在完成doublewrite寫入後,在将double write buffer寫入各表空間檔案,這時是離散寫入。
如果發生了極端情況(斷電),InnoDB再次啟動後,發現了一個Page資料已經損壞,那麼此時就可以從doublewrite buffer中進行資料恢複了。

二double write的缺點是什麼?
位于共享表空間上的double write buffer實際上也是一個檔案,寫DWB會導緻系統有更多的fsync操作, 而硬碟的fsync性能, 是以它會降低mysql的整體性能. 但是并不會降低到原來的50%. 這主要是因為:
1) double write 是一個連接配接的存儲空間, 是以硬碟在寫資料的時候是順序寫, 而不是随機寫, 這樣性能更高.
2) 将資料從double write buffer寫到真正的segment中的時候, 系統會自動合并連接配接空間重新整理的方式, 每次可以重新整理多個pages;
三 double write在恢複的時候是如何工作的?
If there’s a partial page write to the doublewrite buffer itself, the original page will still be on disk in its real location.-
--如果是寫doublewrite buffer本身失敗,那麼這些資料不會被寫到磁盤,InnoDB此時會從磁盤載入原始的資料,然後通過InnoDB的事務日志來計算出正确的資料,重新 寫入到doublewrite buffer.
When InnoDB recovers, it will use the original page instead of the corrupted copy in the doublewrite buffer. However, if the doublewrite buffer succeeds and the write to the page’s real location fails, InnoDB will use the copy in the doublewrite buffer during recovery.
--如果 doublewrite buffer寫成功的話,但是寫磁盤失敗,InnoDB就不用通過事務日志來計算了,而是直接用buffer的資料再寫一遍.
InnoDB knows when a page is corrupt because each page has a checksum at the end; the checksum is the last thing to be written, so if the page’s contents don’t match the checksum, the page is corrupt. Upon recovery, therefore, InnoDB just reads each page in the doublewrite buffer and verifies the checksums. If a page’s checksum is incorrect, it reads the page from its original location.
--在恢複的時候,InnoDB直接比較頁面的checksum,如果不對的話,就從硬碟載入原始資料,再由事務日志 開始推演出正确的資料.是以InnoDB的恢複通常需要較長的時間.
四 我們是否一定需要 double write ?
In some cases, the doublewrite buffer really isn’t necessary—for example, you might want to disable it on slaves. Also, some filesystems (such as ZFS) do the same thing themselves, so it is redundant for InnoDB to do it. You can disable the doublewrite buffer by setting InnoDB_doublewrite to 0.
五 如何使用 double write
InnoDB_doublewrite=1表示啟動double write
show status like 'InnoDB_dblwr%'可以查詢double write的使用情況;
相關參數與狀态
Double write的使用情況:
show status like "%InnoDB_dblwr%";
InnoDB_dblwr_pages_written 從bp flush 到 DBWB的個數
InnoDB_dblwr_writes 寫檔案的次數
每次寫操作合并page的個數= InnoDB_dblwr_pages_written/InnoDB_dblwr_writes
文章可以轉載,必須以連結形式标明出處。
本文轉自 張沖andy 部落格園部落格,原文連結:http://www.cnblogs.com/andy6/p/6938704.html ,如需轉載請自行聯系原作者