前言

在Mysql环境下,常常由于数据磁盘满而导致Mysql故障。下面整理了如何在Mysql环境下做好Mysql的空间清理。

1.查看文件磁盘占用

1.1 查看磁盘空间占用

1
[root@mysqlhost01 /]# df -lh

在这里插入图片描述

1.2 查看目录空间占用

1
2
[root@mysqlhost01 /]# du -sh /usr
5.5G    /usr

在这里插入图片描述

2.Binlog日志清理

2.1.定时自动清理Binlog日志

1
2
3
4
5
6
7
8
9
10
11
12
mysql>show variables like '%expire_logs_days%'--mysql 5.7
mysql> show variables like '%binlog_expire_logs_seconds%'  --mysql8.0
 
mysql8.0
mysql 8开始 expire_logs_days 废弃 启用binlog_expire_logs_seconds设置binlog自动清除日志时间
保存时间 以秒为单位;默认2592000 30天
14400   4小时;86400  1天;259200  3天;
mysql> set global binlog_expire_logs_seconds=86400;
 
mysql5.7
这个默认是0,也就是logs不过期,可通过设置全局的参数,使他临时生效:
mysql>set global expire_logs_days=10;

在这里插入图片描述

2.2 手动删除Binlog日志

1
2
3
4
5
6
7
8
9
10
第一步:登陆进入mysql,并使用 show binary logs; 查看日志文件。
mysql>show binary logs;
第二步:查看正在使用的日志文件:show master status;
mysql>show master status;
当前正在使用的日志文件是mysqlhost01-bin.000010,那么删除日志文件的时候应该排除掉该文件。
删除日志文件的命令:purge binary logs to 'mysqlhost01-bin.000010';
mysql>purge binary logs to 'mysqlhost01-bin.000010';
删除除mysqlhost01-bin.000010以外的日志文件
也可以指定其他文件名,例如mysql-bin.000003。
删除后就能释放大部分空间。

在这里插入图片描述

2.3.Slow日志清理

1
2
3
4
5
6
7
步骤一 查看slow日志模式
mysql>show variables like 'log_output%';
步骤二 查看Slow日志文件位置
show variables like '%slow%';
步骤三 清空Slow日志
[root@mysqlhost01 /]# cd /usr/local/mysql57/mysql5730/data
[root@mysqlhost01 data]# echo "">mysqlhost01-slow.log

在这里插入图片描述

在这里插入图片描述

2.4.Error日志清理

1
2
3
4
5
6
步骤一 查看error日志位置
mysql>show variables like 'log_error';
步骤二 查看error日志大小
[root@mysqlhost01 data]# ll -h log.err
步骤三 清空error日志
echo "">/usr/local/mysql57/mysql5730/data/log.err

在这里插入图片描述

3、表清理

大表,指单个数据文件磁盘占用大于100G,或者单个表数据记录量大于1亿。

3.1.查看表占空间和记录数

1
2
3
4
5
6
7
8
9
select table_schema,table_name,
concat(round((data_length+index_length)/1024/1024/1024,2),'G') as tablesize_gb,
table_rows from information_schema.tables
order by tablesize_gb desc limit 5;
 
table_schema:库名
table_name :表名
tablesize_gb:表占空间大小,以G为单位
table_rows:行数

在这里插入图片描述

3.2 常规表数据清理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
常规表指没达到大表标准的。
Delete
语法:Delete from table_name [ where condition]
Delete 只删除符合条件的数据,不会减少表所占空间。
Delete大量数据后,会存在碎片,需要整理回收碎片空间
optimize table table.name
或者 alter table table.name engine='innodb' (会锁表,注意在业务低谷期执行)
 
 
Truncate
语法:Truncate table table_name
Truncate 删除全表数据,回收所占表空间。
 
Drop
语法:Drop table table_name
Drop 删除全表数据和表结构,回收所占表空间。

到此这篇关于Mysql空间清理的几种具体方法的文章就介绍到这了

posted on 2023-01-12 10:05  李留广  阅读(1030)  评论(0编辑  收藏  举报