MySQL · 2016-10-16 0

Percona-Toolkit系列之pt-fifo-split文件分割利器

1.pt-fifo-split

pt-fifo-split是一个perl语言写的文件分割工具,配置灵活,使用方便。假如我们有一个包含10万行SQL的文件,需要我们在数据库中做更新操作,如果一次性将和这个文件source,串行执行效率低下,而且拖延时间太长,不适合在线操作,为了分解数据库压力,我们可以将文件拆分,分时间段执行每个分割后的SQL文件或者同时执行每个分割后文件。

2.pt-fifo-split原理

pt-fifo-split的原理是这样的,pt-fifo-split按照我们设定的行数,假如是1000,那么pt-fifo-split就每次从源文件取1000行到–fifo指定的临时文件中,然后我们就去读取这个临时文件,放入filename1,当临时文件被读取后,pt-fifo-split又会再次从源文件取1000行放入–fifo指定的临时文件中,我们再次去–fifo指定的临时文件中取数据,放入filename2,依次迭代,达到文件分割的目的。

mysql_ha

3.pt-fifo-split使用

3.1配置

假如现在有个文件diskstats-samples.txt 有2040行,我们按照100行每个文件将其分21个文件(ps:ceil(2040/100)),首先我们需要准备一个获取文件的脚本get_file.sh :

#!/bin/bash
filename="/home/mysql/example"
num=1;
while [ -e /tmp/pt-fifo-split ]; 
do 
        cat /tmp/pt-fifo-split > $filename_$num.txt ;
        let num=num+1;
        sleep 0.1; 
done

注意一定要sleep一下,否则文件不完整

其次我们要给出pt-fifo-split的配置文件

[mysql@hpc02 ~]$ cat fifo_split.cnf 
offset=0  /*从第几行开始分割,0代表从开始分割*/
force     /*如果临时文件存在了,会rm掉,重新创建*/
lines=100   /*控制每次取多少行,也就是我们需要的每个文件的大小*/
fifo=/tmp/pt-fifo-split   /*临时文件位置,和get_file.sh中保持一致*/
statistics   /*打印出运行信息,这样可以查看实时进度*/

3.2运行

首先开启 pt-fifo-split,diskstats-samples.txt 是我们即将分割的文件

[mysql@hpc02 ~]$ pt-fifo-split --config fifo_split.cnf diskstats-samples.txt 
chunks     lines  time  overall  current

然后运行get_file.sh

[mysql@hpc02 ~]$ sh get_file.sh

好了,文件生成了。

[mysql@hpc02 ~]$ ls -l|egrep "[1-9][0-9]?.txt"
-rw-rw-r-- 1 mysql mysql   4961 Oct 16 13:18 10.txt
-rw-rw-r-- 1 mysql mysql   4961 Oct 16 13:18 11.txt
-rw-rw-r-- 1 mysql mysql   4962 Oct 16 13:18 12.txt
-rw-rw-r-- 1 mysql mysql   4963 Oct 16 13:18 13.txt
-rw-rw-r-- 1 mysql mysql   4963 Oct 16 13:18 14.txt
-rw-rw-r-- 1 mysql mysql   4963 Oct 16 13:18 15.txt
-rw-rw-r-- 1 mysql mysql   4963 Oct 16 13:18 16.txt
-rw-rw-r-- 1 mysql mysql   4959 Oct 16 13:18 17.txt
-rw-rw-r-- 1 mysql mysql   4898 Oct 16 13:18 18.txt
-rw-rw-r-- 1 mysql mysql   4953 Oct 16 13:18 19.txt
-rw-rw-r-- 1 mysql mysql   4898 Oct 16 13:18 1.txt
-rw-rw-r-- 1 mysql mysql   4894 Oct 16 13:18 20.txt
-rw-rw-r-- 1 mysql mysql   2065 Oct 16 13:18 21.txt
-rw-rw-r-- 1 mysql mysql   4954 Oct 16 13:18 2.txt
-rw-rw-r-- 1 mysql mysql   4894 Oct 16 13:18 3.txt
-rw-rw-r-- 1 mysql mysql   4854 Oct 16 13:18 4.txt
-rw-rw-r-- 1 mysql mysql   4912 Oct 16 13:18 5.txt
-rw-rw-r-- 1 mysql mysql   4961 Oct 16 13:18 6.txt
-rw-rw-r-- 1 mysql mysql   4961 Oct 16 13:18 7.txt
-rw-rw-r-- 1 mysql mysql   4961 Oct 16 13:18 8.txt
-rw-rw-r-- 1 mysql mysql   4961 Oct 16 13:18 9.txt
[mysql@hpc02 ~]$ for i in {1..21};do echo -n $i.txt"->" ;cat $i.txt|wc -l;done 
1.txt->100
2.txt->100
3.txt->100
4.txt->100
5.txt->100
6.txt->100
7.txt->100
8.txt->100
9.txt->100
10.txt->100
11.txt->100
12.txt->100
13.txt->100
14.txt->100
15.txt->100
16.txt->100
17.txt->100
18.txt->100
19.txt->100
20.txt->100
21.txt->40