MySQL 上億大表優化實踐
MySQL 上億大表優化實踐
背景
XX例項(一主一從)xxx告警中每天凌晨在報SLA報警,該報警的意思是存在一定的主從延遲(若在此時發生主從切換,需要長時間才可以完成切換,要追延遲來保證主從資料的一致性)
XX例項的慢查詢數量最多(執行時間超過1s的sql會被記錄),XX應用那方每天晚上在做刪除一個月前資料的任務
分析
使用pt-query-digest工具分析最近一週的mysql-slow.log
pt-query-digest --since=148h mysql-slow.log | less
結果第一部分
最近一個星期內,總共記錄的慢查詢執行花費時間為25403s,最大的慢sql執行時間為266s,平均每個慢sql執行時間5s,平均掃描的行數為1766萬
結果第二部分
select arrival_record操作記錄的慢查詢數量最多有4萬多次,平均響應時間為4s,delete arrival_record記錄了6次,平均響應時間258s
select xxx_record語句
select arrival_record 慢查詢語句都類似於如下所示,where語句中的引數欄位是一樣的,傳入的引數值不一樣
select count(*) from arrival_record where product_id=26 and receive_time between '2019-03-25 14:00:00' and '2019-03-25 15:00:00' and receive_spend_ms>=0\G
select arrival_record 語句在mysql中最多掃描的行數為5600萬、平均掃描的行數為172萬,推斷由於掃描的行數多導致的執行時間長
檢視執行計劃
explain select count(*) from arrival_record where product_id=26 and receive_time between '2019-03-25 14:00:00' and '2019-03-25 15:00:00' and receive_spend_ms>=0\G;
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: arrival_record
partitions: NULL
type: ref
possible_keys: IXFK_arrival_record
key: IXFK_arrival_record
key_len: 8
ref: const
rows: 32261320
filtered: 3.70
Extra: Using index condition; Using where
1 row in set, 1 warning (0.00 sec)
用到了索引IXFK_arrival_record,但預計掃描的行數很多有3000多w行
show index from arrival_record;
+----------------+------------+---------------------+--------------+--------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+----------------+------------+---------------------+--------------+--------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| arrival_record | 0 | PRIMARY | 1 | id | A | 107990720 | NULL | NULL | | BTREE | | |
| arrival_record | 1 | IXFK_arrival_record | 1 | product_id | A | 1344 | NULL | NULL | | BTREE | | |
| arrival_record | 1 | IXFK_arrival_record | 2 | station_no | A | 22161 | NULL | NULL | YES | BTREE | | |
| arrival_record | 1 | IXFK_arrival_record | 3 | sequence | A | 77233384 | NULL | NULL | | BTREE | | |
| arrival_record | 1 | IXFK_arrival_record | 4 | receive_time | A | 65854652 | NULL | NULL | YES | BTREE | | |
| arrival_record | 1 | IXFK_arrival_record | 5 | arrival_time | A | 73861904 | NULL | NULL | YES | BTREE | | |
+----------------+------------+---------------------+--------------+--------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
show create table arrival_record;
..........
arrival_spend_ms
bigint(20) DEFAULT NULL,
total_spend_ms
bigint(20) DEFAULT NULL,
PRIMARY KEY (id
),
KEYIXFK_arrival_record
(product_id
,station_no
,sequence
,receive_time
,arrival_time
) USING BTREE,
CONSTRAINTFK_arrival_record_product
FOREIGN KEY (product_id
) REFERENCESproduct
(id
) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=614538979 DEFAULT CHARSET=utf8 COLLATE=utf8_bin |
- 該表總記錄數約1億多條,表上只有一個複合索引,product_id欄位基數很小,選擇性不好
- 傳入的過濾條件 where product_id=26 and receive_time between '2019-03-25 14:00:00' and '2019-03-25 15:00:00' and receive_spend_ms>=0 沒有station_nu欄位,使用不到複合索引 IXFK_arrival_record的
product_id
,station_no
,sequence
,receive_time
這幾個欄位- 根據最左字首原則,select arrival_record只用到了複合索引IXFK_arrival_record的第一個欄位product_id,而該欄位選擇性很差,導致掃描的行數很多,執行時間長
- receive_time欄位的基數大,選擇性好,可對該欄位單獨建立索引,select arrival_record sql就會使用到該索引
現在已經知道了在慢查詢中記錄的select arrival_record where語句傳入的引數欄位有 product_id,receive_time,receive_spend_ms,還想知道對該表的訪問有沒有通過其它欄位來過濾了?
神器tcpdump出場的時候到了
使用tcpdump抓包一段時間對該表的select語句
tcpdump -i bond0 -s 0 -l -w - dst port 3316 | strings | grep select | egrep -i 'arrival_record' >/tmp/select_arri.log
獲取select 語句中from 後面的where條件語句
IFS_OLD=$IFS IFS=$'\n' for i in `cat /tmp/select_arri.log `;do echo ${i#*'from'}; done | less IFS=$IFS_OLD
arrival_record arrivalrec0_ where arrivalrec0_.sequence='2019-03-27 08:40' and arrivalrec0_.product_id=17 and arrivalrec0_.station_no='56742'
arrival_record arrivalrec0_ where arrivalrec0_.sequence='2019-03-27 08:40' and arrivalrec0_.product_id=22 and arrivalrec0_.station_no='S7100'
arrival_record arrivalrec0_ where arrivalrec0_.sequence='2019-03-27 08:40' and arrivalrec0_.product_id=24 and arrivalrec0_.station_no='V4631'
arrival_record arrivalrec0_ where arrivalrec0_.sequence='2019-03-27 08:40' and arrivalrec0_.product_id=22 and arrivalrec0_.station_no='S9466'
arrival_record arrivalrec0_ where arrivalrec0_.sequence='2019-03-27 08:40' and arrivalrec0_.product_id=24 and arrivalrec0_.station_no='V4205'
arrival_record arrivalrec0_ where arrivalrec0_.sequence='2019-03-27 08:40' and arrivalrec0_.product_id=24 and arrivalrec0_.station_no='V4105'
arrival_record arrivalrec0_ where arrivalrec0_.sequence='2019-03-27 08:40' and arrivalrec0_.product_id=24 and arrivalrec0_.station_no='V4506'
arrival_record arrivalrec0_ where arrivalrec0_.sequence='2019-03-27 08:40' and arrivalrec0_.product_id=24 and arrivalrec0_.station_no='V4617'
arrival_record arrivalrec0_ where arrivalrec0_.sequence='2019-03-27 08:40' and arrivalrec0_.product_id=22 and arrivalrec0_.station_no='S8356'
arrival_record arrivalrec0_ where arrivalrec0_.sequence='2019-03-27 08:40' and arrivalrec0_.product_id=22 and arrivalrec0_.station_no='S8356'
- select 該表 where條件中有product_id,station_no,sequence欄位,可以使用到複合索引IXFK_arrival_record的前三個欄位
綜上所示,優化方法為,刪除複合索引IXFK_arrival_record,建立複合索引idx_sequence_station_no_product_id,並建立單獨索引indx_receive_time
delete xxx_record語句
該delete操作平均掃描行數為1.1億行,平均執行時間是262s
delete語句如下所示,每次記錄的慢查詢傳入的引數值不一樣
delete from arrival_record where receive_time < STR_TO_DATE('2019-02-23', '%Y-%m-%d')\G
執行計劃
explain select * from arrival_record where receive_time < STR_TO_DATE('2019-02-23', '%Y-%m-%d')\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: arrival_record
partitions: NULL
type: ALL
possible_keys: NULL
key: NULL
key_len: NULL
ref: NULL
rows: 109501508
filtered: 33.33
Extra: Using where
1 row in set, 1 warning (0.00 sec)
- 該delete語句沒有使用索引(沒有合適的索引可用),走的全表掃描,導致執行時間長
- 優化方法也是 建立單獨索引indx_receive_time(receive_time)
測試
拷貝arrival_record表到測試例項上進行刪除重新索引操作
XX例項arrival_record表資訊
du -sh /datas/mysql/data/3316/cq_new_cimiss/arrival_record*
12K /datas/mysql/data/3316/cq_new_cimiss/arrival_record.frm
48G /datas/mysql/data/3316/cq_new_cimiss/arrival_record.ibd
select count( ) from
cq_new_cimiss
.arrival_record
;
+-----------+
| count() |
+-----------+
| 112294946 |
+-----------+
1億多記錄數
SELECT
table_name,
CONCAT(FORMAT(SUM(data_length) / 1024 / 1024,2),'M') AS dbdata_size,
CONCAT(FORMAT(SUM(index_length) / 1024 / 1024,2),'M') AS dbindex_size,
CONCAT(FORMAT(SUM(data_length + index_length) / 1024 / 1024 / 1024,2),'G') AStable_size(G)
,
AVG_ROW_LENGTH,table_rows,update_time
FROM
information_schema.tables
WHERE table_schema = 'cq_new_cimiss' and table_name='arrival_record';
+----------------+-------------+--------------+------------+----------------+------------+---------------------+
| table_name | dbdata_size | dbindex_size | table_size(G) | AVG_ROW_LENGTH | table_rows | update_time |
+----------------+-------------+--------------+------------+----------------+------------+---------------------+
| arrival_record | 18,268.02M | 13,868.05M | 31.38G | 175 | 109155053 | 2019-03-26 12:40:17 |
+----------------+-------------+--------------+------------+----------------+------------+---------------------+
磁碟佔用空間48G,mysql中該表大小為31G,存在17G左右的碎片,大多由於刪除操作造成的(記錄被刪除了,空間沒有回收)
備份還原該表到新的例項中,刪除原來的複合索引,重新新增索引進行測試
mydumper並行壓縮備份
user=root passwd=xxxx socket=/datas/mysql/data/3316/mysqld.sock db=cq_new_cimiss table_name=arrival_record backupdir=/datas/dump_$table_name mkdir -p $backupdir nohup echo `date +%T` && mydumper -u $user -p $passwd -S $socket -B $db -c -T $table_name -o $backupdir -t 32 -r 2000000 && echo `date +%T` &
並行壓縮備份所花時間(52s)和佔用空間(1.2G,實際該表佔用磁碟空間為48G,mydumper並行壓縮備份壓縮比相當高!)
Started dump at: 2019-03-26 12:46:04 ........ Finished dump at: 2019-03-26 12:46:56 du -sh /datas/dump_arrival_record/ 1.2G /datas/dump_arrival_record/
拷貝dump資料到測試節點
scp -rp /datas/dump_arrival_record root@10.230.124.19:/datas
多執行緒匯入資料
time myloader -u root -S /datas/mysql/data/3308/mysqld.sock -P 3308 -p root -B test -d /datas/dump_arrival_record -t 32
real 126m42.885s
user 1m4.543s
sys 0m4.267s
邏輯匯入該表後磁碟佔用空間
du -h -d 1 /datas/mysql/data/3308/test/arrival_record.*
12K /datas/mysql/data/3308/test/arrival_record.frm
30G /datas/mysql/data/3308/test/arrival_record.ibd
沒有碎片,和mysql的該表的大小一致
cp -rp /datas/mysql/data/3308 /datas
分別使用online DDL和 pt-osc工具來做刪除重建索引操作
先刪除外來鍵,不刪除外來鍵,無法刪除複合索引,外來鍵列屬於複合索引中第一列
nohup bash /tmp/ddl_index.sh &
2019-04-04-10:41:39 begin stop mysqld_3308
2019-04-04-10:41:41 begin rm -rf datadir and cp -rp datadir_bak
2019-04-04-10:46:53 start mysqld_3308
2019-04-04- 10:46:59 online ddl begin
2019-04-04- 11:20:34 onlie ddl stop
2019-04-04-11:20:34 begin stop mysqld_3308
2019-04-04-11:20:36 begin rm -rf datadir and cp -rp datadir_bak
2019-04-04-11:22:48 start mysqld_3308
2019-04-04- 11:22:53 pt-osc begin
2019-04-04- 12:19:15 pt-osc stop
online ddl 花費時間為34 分鐘,pt-osc花費時間為57 分鐘,使用onlne ddl時間約為pt-osc工具時間的一半
做DDL 參考
實施
由於是一主一從例項,應用是連線的vip,刪除重建索引採用online ddl來做。停止主從複製後,先在從例項上做(不記錄binlog),主從切換,再在新切換的從例項上做(不記錄binlog)
function red_echo () { local what="$*" echo -e "$(date +%F-%T) ${what}" } function check_las_comm(){ if [ "$1" != "0" ];then red_echo "$2" echo "exit 1" exit 1 fi } red_echo "stop slave" mysql -uroot -p$passwd --socket=/datas/mysql/data/${port}/mysqld.sock -e"stop slave" check_las_comm "$?" "stop slave failed" red_echo "online ddl begin" mysql -uroot -p$passwd --socket=/datas/mysql/data/${port}/mysqld.sock -e"set sql_log_bin=0;select now() as ddl_start;ALTER TABLE $db_.\`${table_name}\` DROP FOREIGN KEY FK_arrival_record_product,drop index IXFK_arrival_record,add index idx_product_id_sequence_station_no(product_id,sequence,station_no),add index idx_receive_time(receive_time);select now() as ddl_stop" >>${log_file} 2>& 1 red_echo "onlie ddl stop" red_echo "add foreign key" mysql -uroot -p$passwd --socket=/datas/mysql/data/${port}/mysqld.sock -e"set sql_log_bin=0;ALTER TABLE $db_.${table_name} ADD CONSTRAINT _FK_${table_name}_product FOREIGN KEY (product_id) REFERENCES cq_new_cimiss.product (id) ON DELETE NO ACTION ON UPDATE NO ACTION;" >>${log_file} 2>& 1 check_las_comm "$?" "add foreign key error" red_echo "add foreign key stop" red_echo "start slave" mysql -uroot -p$passwd --socket=/datas/mysql/data/${port}/mysqld.sock -e"start slave" check_las_comm "$?" "start slave failed"
執行時間
2019-04-08-11:17:36 stop slave
mysql: [Warning] Using a password on the command line interface can be insecure.
ddl_start
2019-04-08 11:17:36
ddl_stop
2019-04-08 11:45:13
2019-04-08-11:45:13 onlie ddl stop
2019-04-08- 11:45:13 add foreign key
mysql: [Warning] Using a password on the command line interface can be insecure.
2019-04-08-12:33:48 add foreign key stop
2019-04-08- 12:33:48 start slave
刪除重建索引花費時間為28分鐘,新增外來鍵約束時間為48分鐘
再次檢視delete 和select語句的執行計劃
explain select count(*) from arrival_record where receive_time < STR_TO_DATE('2019-03-10', '%Y-%m-%d')\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: arrival_record
partitions: NULL
type: range
possible_keys: idx_receive_time
key: idx_receive_time
key_len: 6
ref: NULL
rows: 7540948
filtered: 100.00
Extra: Using where; Using index
explain select count(*) from arrival_record where product_id=26 and receive_time between '2019-03-25 14:00:00' and '2019-03-25 15:00:00' and receive_spend_ms>=0\G;
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: arrival_record
partitions: NULL
type: range
possible_keys: idx_product_id_sequence_station_no,idx_receive_time
key: idx_receive_time
key_len: 6
ref: NULL
rows: 291448
filtered: 16.66
Extra: Using index condition; Using where
都使用到了idx_receive_time 索引,掃描的行數大大降低
索引優化後
delete 還是花費了77s時間
delete from arrival_record where receive_time < STR_TO_DATE('2019-03-10', '%Y-%m-%d')\G
delete 語句通過receive_time的索引刪除300多萬的記錄花費77s時間*
delete大表優化為小批量刪除
應用端已優化成每次刪除10分鐘的資料(每次執行時間1s左右),xxx中沒在出現SLA(主從延遲告警)
另一個方法是通過主鍵的順序每次刪除20000條記錄
#得到滿足時間條件的最大主鍵ID #通過按照主鍵的順序去 順序掃描小批量刪除資料 #先執行一次以下語句 SELECT MAX(id) INTO @need_delete_max_id FROM `arrival_record` WHERE receive_time<'2019-03-01' ; DELETE FROM arrival_record WHERE id<@need_delete_max_id LIMIT 20000; select ROW_COUNT(); #返回20000 #執行小批量delete後會返回row_count(), 刪除的行數 #程式判斷返回的row_count()是否為0,不為0執行以下迴圈,為0退出迴圈,刪除操作完成 DELETE FROM arrival_record WHERE id<@need_delete_max_id LIMIT 20000; select ROW_COUNT(); #程式睡眠0.5s
總結
- 表資料量太大時,除了關注訪問該表的響應時間外,還要關注對該表的維護成本(如做DDL表更時間太長,delete歷史資料)
- 對大表進行DDL操作時,要考慮表的實際情況(如對該表的並發表,是否有外來鍵)來選擇合適的DDL變更方式
- 對大資料量表進行delete,用小批量刪除的方式,減少對主例項的壓力和主從延遲
About Me
........................................................................................................................ ● 本文作者:小麥苗,部分內容整理自網路,若有侵權請聯絡小麥苗刪除 ● 本文在個人微 信公眾號( DB寶)上有同步更新 ● QQ群號: 230161599 、618766405,微信群私聊 ● 個人QQ號(646634621),微 訊號(db_bao),註明新增緣由 ● 於 2020年11月完成 ● 最新修改時間:2020年11月 ● 版權所有,歡迎分享本文,轉載請保留出處 ........................................................................................................................ ● 小麥苗的微店: https://weidian.com/s/793741433?wfr=c&ifr=shopdetail ● 小麥苗出版的資料庫類叢書: http://blog.itpub.net/26736162/viewspace-2142121/ ● 小麥苗OCP、OCM、高可用、DBA學習班: http://blog.itpub.net/26736162/viewspace-2148098/ ● 資料庫筆試面試題庫及解答: http://blog.itpub.net/26736162/viewspace-2134706/ ........................................................................................................................ 請掃描下面的二維碼來關注小麥苗的微 信公眾號( DB寶)及QQ群(230161599、618766405)、新增小麥苗微 信(db_bao), 學習最實用的資料庫技術。
........................................................................................................................ |
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/26736162/viewspace-2732253/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- Mysql 慢查詢優化實踐MySql優化
- MySQL表優化MySql優化
- Mysql表引擎優化MySql優化
- MySQL大表優化方案MySql優化
- 從理論到實踐,Mysql查詢優化剖析MySql優化
- MySQL表連線及其優化MySql優化
- SOFARPC 效能優化實踐(上)| SOFAChannel#2 直播整理RPC優化
- 小程式優化實踐優化
- 3.1 MYSQL分庫分表實踐MySql
- MySQL——索引優化實戰MySql索引優化
- Apache HBase MTTR 優化實踐Apache優化
- 效能優化,實踐淺談優化
- 乾貨!MySQL大表優化方案(1)MySql優化
- 優酷 Android 構建速度優化實踐Android優化
- MySQL 優化實戰記錄MySql優化
- mysql優化 | 儲存引擎,建表,索引,sql的優化建議MySql優化儲存引擎索引
- 前端效能優化原理與實踐前端優化
- 前端 Web gRPC 實踐和優化前端WebRPC優化
- WebRTC 架構優化及實踐Web架構優化
- ⚠️Flutter 效能優化實踐 總結⚠️Flutter優化
- 大檔案排序優化實踐排序優化
- App記憶體優化-實踐APP記憶體優化
- FlutterWeb效能優化探索與實踐FlutterWeb優化
- Taro編譯打包優化實踐編譯優化
- Flutter效能優化實踐之TimelineFlutter優化
- 2022 前端效能優化最佳實踐前端優化
- 實踐分享 - MySQL優化 - 查詢去年待流失客戶的交易額MySql優化
- MySql 日常指導,及大表優化思路MySql優化
- 讀小程式效能優優化實踐-筆記優化筆記
- TiDB 效能分析&效能調優&優化實踐大全TiDB優化
- MySQL 優化六(InnoDB 下 update 資料出現表鎖之優化)MySql優化
- 《MySQL效能優化和高可用架構實踐》簡介與推薦序MySql優化架構
- 搜狐服務架構優化實踐架構優化
- Nodejs Docker 映象體積優化實踐NodeJSDocker優化
- React中型專案的優化實踐React優化
- HybridDBforPostgreSQL,Greenplum寫入效能優化實踐SQL優化
- Vue 專案效能優化 — 實踐指南Vue優化
- Canvas 動畫的效能優化實踐Canvas動畫優化