MySQL兩階段提交


參數介紹


innodb_flush_log_at_trx_commit

0: 每隔1s,系統后台線程刷log buffer,也就是把redo日志刷盤,這里會調用fsync,所以可能丟失最后1s的事務。

1: 每次commit時,刷redo日志,確定fsync刷盤

2: 每次提交時,刷redo日志到文件系統,不調用fsync刷盤,5.6.6之前是每隔1s刷盤,之后的版本是通過參數innodb_flush_log_at_timeout設置,默認也是1s。所以也可能丟最后一秒的事務。如果有掉電保護組件的話,可以開啟。

sync_binlog

表示每多少個sync事件觸發一次真正的binlog fsync刷盤,默認是1,表示每次commit時binlog都會fsync。

兩階段提交


這個兩階段提交不是分布式事務的兩階段提交,而是在開啟binlog之后,redo與binlog的兩階段提交。 兩階段提交,首先redo log prepare,然后寫binlog,最后redo log commit.

  • 如果redo log prepare之后,binlog之前宕機,則回滾事務,日志如下:
2015-07-29 17:03:18 21957 [Note] Starting crash recovery... 2015-07-29 17:03:18 7ffff7fe4780 InnoDB: Starting recovery for XA transactions... 2015-07-29 17:03:18 7ffff7fe4780 InnoDB: Transaction 35077 in prepared state after recovery 2015-07-29 17:03:18 7ffff7fe4780 InnoDB: Transaction contains changes to 1 rows 2015-07-29 17:03:18 7ffff7fe4780 InnoDB: 1 transactions in prepared state after recovery 2015-07-29 17:03:18 21957 [Note] Found 1 prepared transaction(s) in InnoDB 2015-07-29 17:03:18 21957 [Note] rollback xid 'MySQLXid\1\0\0\0\0\0\0\0\6\0\0\0\0\0\0\0'
  • 如果binlog寫入之后宕機,則recover事務。
2015-07-29 17:06:23 7ffff7fe4780 InnoDB: Starting recovery for XA transactions... 2015-07-29 17:06:23 7ffff7fe4780 InnoDB: Transaction 35590 in prepared state after recovery 2015-07-29 17:06:23 7ffff7fe4780 InnoDB: Transaction contains changes to 1 rows 2015-07-29 17:06:23 7ffff7fe4780 InnoDB: 1 transactions in prepared state after recovery 2015-07-29 17:06:23 22040 [Note] Found 1 prepared transaction(s) in InnoDB 2015-07-29 17:06:23 22040 [Note] commit xid 'MySQLXid\1\0\0\0\0\0\0\0\6\0\0\0\0\0\0\0' 2015-07-29 17:06:23 22040 [Note] Crash recovery finished.

什么情況下會出現binlog寫入了,但是實際這條數據不存在庫中?

innodb_flush_log_at_trx_commit 為0, sync_binlog=1,此時redo log沒有刷盤,binlog刷盤了,recover的時候不會根據binlog恢復。

所以強烈建議這兩個參數都設置成1.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM