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.
安心做技术