摘要
binlog相关
MySQL的二进制日志binlog可以说是MySQL最重要的日志,它记录了所有的DDL和DML语句(除了数据查询语句select),其以事件形式记录,还包含语句所执行的消耗的时间,MySQL的二进制日志是事务安全型的,所以binlog内记录的是事务提交成功后的内容。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 # 查看bin‐log是否开启 mysql> show variables like '%log_bin%' ; + | Variable_name | Value | + | log_bin | ON | | log_bin_basename | / usr/ local / soft/ mysql8/ datas/ mysql/ mysql- bin | | log_bin_index | / usr/ local / soft/ mysql8/ datas/ mysql/ mysql- bin.index | | log_bin_trust_function_creators | OFF | | log_bin_use_v1_row_events | OFF | | sql_log_bin | ON | + # 查看最后一个bin‐log日志的相关信息 mysql> show master status; + | File | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set | + | mysql- bin.000012 | 138605 | | | | + # 会多一个最新的bin‐log日志 mysql> flush logs; Query OK, 0 rows affected (0.02 sec) mysql> show master status; + | File | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set | + | mysql- bin.000013 | 157 | | | | + 1 row in set (0.00 sec)# 清空所有的bin‐log日志 mysql> reset master; Query OK, 0 rows affected (0.02 sec) mysql> show master status; + | File | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set | + | mysql- bin.000001 | 157 | | | | + 1 row in set (0.00 sec)
1 2 mysqlbinlog --no-defaults /usr/local/soft/mysql8/datas/mysql/mysql-bin.000001
如下为查看binlog日志的内容片段,end_log_pos
后面的就是Position的值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 BEGIN /*!*/; BINLOG ' NwQ0YxPqDAAAOAAAAG8BAAAAALoAAAAAAAEABHRlc3QABGZpbG0AAgMPAh4AAgEBAAIBISrPO08= NwQ0Yx7qDAAALQAAAJwBAAAAALoAAAAAAAEAAgAC/wAEAAAABHRlc3Qwdcg/ ' /*!*/;COMMIT/*!*/;
常用的恢复方法
1 2 3 4 5 6 7 8 mysqlbinlog --no-defaults mysql-bin.000001 | mysql -uroot -p test (数据库名) mysqlbinlog --no-defaults --start-position="367" --stop-position="443" mysql-bin.000001 | mysql -uroot -p test (数据库) mysqlbinlog --no-defaults --stop-date= "2022‐09‐28 08:22:15" --start-date= "2022‐09‐28 08:22:15" mysql-bin.000001 | mysql -uroot -p test (数据库)
一个数据恢复的小示例
1 mysqldump -uroot -ppassword -B dbName > $bakpath /dbName_$(date +%F).sql
1 cp /usr/local/soft/mysql8/datas/mysql/mysql-bin.* $bakpath /
1 rm -rf /usr/local/soft/mysql8/datas/mysql/*
1 2 mysqld --user=mysql --initialize-insecure systemctl start mysqld
1 mysql < $bakpath/ dbName_$(date + % F).sql
1 2 mysqlbinlog --no-defaults --start-date="2022-11-10 12:30:30" $bakpath /mysql-bin.* | mysql dbName
注意
如果数据库开启了GTID,需要先关闭再导入binlog数据,否则不能导入binlog数据
临时关闭方式: 更改 GTID_MODE 状态顺序为 ON<->ON_PERMISSIVE<->OFF_PERMISSIVE<->OFF ,需要按照顺序依次改变。
1 2 3 4 5 6 7 8 # 查看 GTID_MODE 当前状态 show global variables like 'gtid_mode' ;# 修改GTID_MODE 状态为 ON_PERMISSIVE set @@GLOBAL .GTID_MODE= ON_PERMISSIVE;# 修改GTID_MODE 状态为 OFF_PERMISSIVE set @@GLOBAL .GTID_MODE= OFF_PERMISSIVE;# 修改GTID_MODE 状态为 OFF set @@GLOBAL .GTID_MODE= OFF;