代码改变世界

mysql的binlog安全删除

2016-03-15 13:17  youxin  阅读(5120)  评论(0编辑  收藏  举报

理论上,应该在配置文件/etc/my.cnf中加上binlog过期时间的配置项,expire_logs_days = 10

但是如果没有加这一项,随着产生越来越多的binlog,磁盘被吃掉了不少。可以直接删除binlog文件,但是可以通过mysql提供的工具来删除更安全。因为purge会更新mysql-bin.index中的条目,而直接删除的话,mysql-bin.index文件不会更新。mysql-bin.index的作用是加快查找binlog文件的速度。

先help一下吧:

mysql> help purge
Name: 'PURGE MASTER LOGS'
Description:
Syntax:
PURGE {MASTER | BINARY} LOGS TO 'log_name'
PURGE {MASTER | BINARY} LOGS BEFORE 'date'

(purge:肃清; 清除 )

Deletes all the binary logs listed in the log index prior to the
specified log or date. The logs also are removed from the list recorded
in the log index file, so that the given log becomes the first.

This statement has no effect if the --log-bin option has not been
enabled.

URL: http://dev.mysql.com/doc/refman/5.0/en/purge-master-logs.html

Examples:
PURGE MASTER LOGS TO 'mysql-bin.010';
PURGE MASTER LOGS BEFORE '2003-04-02 22:46:26';

 

两种方法都可用。第一个是删除至某一个文件为止,第二个是删除到某个日期为止。

比如我们让它保留近3天的log,可以这样

PURGE MASTER LOGS BEFORE '2010-10-17 00:00:00';

 

看下执行前后的文件数:

执行前:

part2# ls mysql-bin.*|wc -l
     243

执行purge:

mysql> PURGE MASTER LOGS BEFORE '2010-10-17 00:00:00';
Query OK, 0 rows affected (0.02 sec)

执行后:

part2# ls mysql-bin.* | wc -l
      88

可见把17号前的binlog全部删除了。

 

需要注意的是:最好到slave上面去看下当前同步到那个binlog文件了,用show slave status查看。否则,master上删多了的话,就造成slave缺失日志文件而导致数据不一致了。


 

默认情况下mysql会一直保留mysql-bin文件,这样到一定时候,磁盘可能会被撑满,这时候是否可以删除这些文件呢,是否可以安全删除,是个问题。

首先要说明一下,这些文件都是mysql的日志文件,如果不做主从复制的话,基本上是没用的,虽然没用,但是不建议使用rm命令删除,这样有可能会不安全,正确的方法是通过mysql的命令去删除。

mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2819416
Server version: 5.5.24-0ubuntu0.12.04.1-log (Ubuntu)

Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> reset master;
Query OK, 0 rows affected (3 min 37.65 sec)

其实关键的命令就是reset master;这个命令会清空mysql-bin文件。

另外如果你的mysql服务器不需要做主从复制的话,建议通过修改my.cnf文件,来设置不生成这些文件,只要删除my.cnf中的下面一行就可以了。

log-bin=mysql-bin

如果你需要复制,最好控制一下这些日志文件保留的天数,可以通过下面的配置设定日志文件保留的天数:

expire_logs_days = 7

表示保留7天的日志,这样老日志会自动被清理掉。

 参考:
http://blog.csdn.net/atco/article/details/24259333