Pt-online支持在不锁表的情况下修改表结构
使用场景
大数据量表结构修改
ALTER TABLE的执行时间会随着表数据量的增加而增加
Mysql有三种级别的锁,分别为:行级锁、页级锁、表级锁。修改表结构是表级锁,在修改期间会影响写入操作,而且会提高数据库CPU、IO的消耗,使MySQL服务器性能降低
原理
其实通过成功打印就能看出原理:
以下是成功输出
Altering `jsw-spoc`.`user_wx`...
Creating new table...
Created new table jsw-spoc._user_wx_new OK.
Altering new table...
Altered `jsw-spoc`.`_user_wx_new` OK.
2019-07-23T15:55:04 Creating triggers...
2019-07-23T15:55:05 Created triggers OK.
2019-07-23T15:55:05 Copying approximately 17 rows...
2019-07-23T15:55:06 Copied rows OK.
2019-07-23T15:55:06 Analyzing new table...
2019-07-23T15:55:11 Swapping tables...
2019-07-23T15:55:16 Swapped original and new tables OK.
2019-07-23T15:55:16 Dropping old table...
2019-07-23T15:55:18 Dropped old table `jsw-spoc`.`_user_wx_old` OK.
2019-07-23T15:55:18 Dropping triggers...
2019-07-23T15:55:18 Dropped triggers OK.
Successfully altered `jsw-spoc`.`user_wx`.
1、新建一张_new后缀的新表
2、更新新表
3、在原表添加触发器triggers 分别是DELETE/UPDATE/INSERT,目的就是在转移期间数据同步(原表发生数据更改可以通过触发器同步到_new后缀的新表)
4、将老表改新名字,将新表改老名字
5、删除老表
下载地址
https://www.percona.com/downloads/percona-toolkit/LATEST/
安装
解压缩就可以
依赖工具包
yum install perl-DBI
yum install perl-DBD-MySQL
yum install perl-Time-HiRes
yum install perl-IO-Socket-SSL
基本命令
--user= 用户名
--password= 密码
--host= 地址
P=3306 端口号
D= 库名
t= 表名
--alter ALTER TABLE sql
--execute 执行修改表结构
--charset=utf8 设置编码
--no-version-check 不进行版本检查,建议添加
比如要新增一个字段
./pt-online-schema-change --charset=utf8 --no-version-check --user=user --password=password --host=127.0.0.1 P=3306,D='jsw-spoc',t=tags --alter 'add column det tinyint(4) DEFAULT NULL' --execute
下面是可能遇到的错误
错误:pt-online Can’t locate Digest/MD5.pm in @INC (@INC contains:
解决: yum -y install perl-Digest-MD5
错误:
权限不够
解决:(偷懒方法)
错误:
解决:书写格式错误
最终结果
Altering `jsw-spoc`.`user_wx`...
Creating new table...
Created new table jsw-spoc._user_wx_new OK.
Altering new table...
Altered `jsw-spoc`.`_user_wx_new` OK.
2019-07-23T15:55:04 Creating triggers...
2019-07-23T15:55:05 Created triggers OK.
2019-07-23T15:55:05 Copying approximately 17 rows...
2019-07-23T15:55:06 Copied rows OK.
2019-07-23T15:55:06 Analyzing new table...
2019-07-23T15:55:11 Swapping tables...
2019-07-23T15:55:16 Swapped original and new tables OK.
2019-07-23T15:55:16 Dropping old table...
2019-07-23T15:55:18 Dropped old table `jsw-spoc`.`_user_wx_old` OK.
2019-07-23T15:55:18 Dropping triggers...
2019-07-23T15:55:18 Dropped triggers OK.
Successfully altered `jsw-spoc`.`user_wx`.