最近需要对一个对数据表做清理的操作,这个环境是一个线上业务,因为各种原因,表中的数据比较臃肿,而磁盘空间又比较小,所以经常导致磁盘空间爆满,和业务确认后对数据做定时删除,实现方式如下,以下针对小项目。
1. 开启事件调度器
- set global event_scheduler= ON; show variables like '%event_scheduler%';#my.cnf增加参数event_scheduler = on
2. 创建日志删除记录表
- CREATE TABLE IF NOT EXISTS mq_log( name VARCHAR(400) NOT NULL COMMENT '删除信息', row INT COMMENT '删除行数', del_time TIMESTAMP COMMENT '删除时间') COMMENT = '日志删除记录表';
3. 创建日志删除存储过程
这里主要用了异常记录、影响行数记录、事务处理几个特点
- drop procedure if exists del_mq_log;DELIMITER // create procedure del_mq_log()BEGIN DECLARE affect_rows INT; DECLARE affect_rows2 INT; DECLARE affect_rows3 INT; declare v_commit int default 2; -- 定义事务用,1为正常,-10为失败 declare msg text;-- 记录错误信息 -- 异常的时候msg捕获报错信息 declare continue handler for sqlexception begin get diagnostics condition 1 msg = message_text;set v_commit = -10; end ; start transaction; -- 设置事务 delete from lcp_mq_record where last_update_date < DATE_SUB(CURDATE(),INTERVAL 30 DAY); select ROW_COUNT() into @affect_rows; delete from lcp_dd_service_record where last_update_date < DATE_SUB(CURDATE(),INTERVAL 30 DAY); select ROW_COUNT() into @affect_rows2; delete from lcp_api_service_record where last_update_date < DATE_SUB(CURDATE(),INTERVAL 30 DAY); select ROW_COUNT() into @affect_rows3; insert into mq_log values('删除lcp_mq_record成功',@affect_rows,now()),('删除lcp_dd_service_record成功',@affect_rows2,now()),('删除lcp_api_service_record 成功',@affect_rows3,now()); -- 记录删除情况 -- 异常回滚且记录日志 if v_commit = -10 then ROLLBACK; insert into mq_log values(msg,0,now()); end if ;END//DELIMITER ;
4. 创建一个每天凌晨1点执行存储过程的定时任务
- DROP event IF EXISTS e_del_mqlog; CREATE EVENT e_del_mqlog ON SCHEDULE EVERY 1 DAY STARTS DATE_ADD(DATE_ADD(CURDATE(), INTERVAL 1 DAY), INTERVAL 1 HOUR) DO call del_mq_log();
5. 第一次删除需做回收
- alter table lcp_mq_record engine=innodb;alter table lcp_dd_service_record engine=innodb;alter table lcp_api_service_record engine=innodb;