MySQL 主从数据校验/修复

主从数据校验

维度:

  1个月对现网数据做一次数据校验

  如果发生主从切换,当天要做一次数据校验

校验工具:

  pt-table-checksum

修复工具:

  pt-table-sync

pt-table-checksum 

原理

在数据库创建表: checksums

每次取count(*) where id > 0 and id <= 1000 数据(this_cnt),做hash_code运算(this_crc)

主库:select count(*) from tb where id > 0 and id <= 1000;

主从分别执行函数,生成各自的cnt,crc的值 

set binlog_format = 'statement'

replace into percona.checksum( db, tb1, chunk, chunk_index, lower_boundary, upper_boundary, this_cnt, this_crc) select xxxxxx 

将主库的this_cnt, this_crc值更新到 master_cnt, master_crc 里。

select this_cnt, this_crc from checksum where db = 'xx'  and tb = 'xx' and chunk =  xx;

update checksum set master_cnt = this_cnt.value, master_crc = this_crc.value where db = 'xx' and tb = 'xx' and chunk = xx;

对比从库的this_cnt, this_crc值 和 master_cnt, master_crc 

select db,tb1,sum(this_cnt) as total_rows, count(*) as chunks from checksums where (master_cnt <>this_cnt or master_crc <> this_crc or isnull(master_crc) <> isnull(this_crc)) group by db,tb1;

使用

--recursion-method=hosts:
需要从库配置文件添加从库信息:
report_host=172.18.10.198
主库show slave hosts时,才能够找到从库。

pt-table-checksum  --host=172.18.10.197 --port=3306 --databases=xxxx   -uxxxx -p --nocheck-replication-filters --replicate=percona.checksums --nocheck-binlog-format --nocheck-plan --recursion-method=hosts

--nocheck-replication-filters :不检查复制过滤器,建议启用。后面可以用--databases来指定需要检查的数据库。
--no-check-binlog-format      : 不检查复制的binlog模式,要是binlog模式是ROW,则会报错。
--replicate-check-only :只显示不同步的信息。
--replicate=   :把checksum的信息写入到指定表中,建议直接写到被检查的数据库当中。 
--databases=   :指定需要被检查的数据库,多个则用逗号隔开。
--tables=      :指定需要被检查的表,多个用逗号隔开
h=127.0.0.1    :Master的地址
u=root         :用户名
p=123456       :密码
P=3306         :端口
 
TS            :完成检查的时间。
ERRORS        :检查时候发生错误和警告的数量。
DIFFS         :0表示一致,1表示不一致。当指定--no-replicate-check时,会一直为0,当指定--replicate-check-only会显示不同的信息。
ROWS          :表的行数。
CHUNKS        :被划分到表中的块的数目。
SKIPPED       :由于错误或警告或过大,则跳过块的数目。
TIME          :执行的时间。
TABLE         :被检查的表名。

pt-table-sync

原理

 通过pt-table_checksum查到出错的chunk,进行折半查找,找到出错记录。

主库设置

binlog_format='statement'

主库存在,从库不存在。主库执行delete from tb where id = xxx;

主库存在,从库存在,主库replace into ,将记录重新插入一次。从库会将正确数据插入进去。

使用

恢复数据:第一个h是master,第二个h是slave,表必须有主键。先--print查看然后再执行
打印SQL
pt-table-sync --charset=utf8  --databases --no-check-slave dsn=u=root,p=root,h=172.18.10.198,P=3306 dsn=u=root,p=root,h=172.18.10.198,P=3307  --print
执行
pt-table-sync --charset=utf8  --databases=db1 --no-check-slave dsn=u=root,p=root,h=172.18.10.198,P=3306 dsn=u=root,p=root,h=172.18.10.198,P=3307  --execute
 
--ignore-databases=指定要忽略的库
--databases=指定库
--tables=指定表
 --print   查看执行语句
--execute  执行
--no-check-slave不检查desitination是否为从库 

猜你喜欢

转载自www.cnblogs.com/yujiaershao/p/11270897.html