運行時間比較長,長時間未提交的事務就能夠稱爲大事務html
注:本文的sql的操做都是基於mysql5.7版本mysql
以查詢執行時間超過10秒的事務爲例:面試
select * from information_schema.innodb_trx where TIME_TO_SEC(timediff(now(),trx_started))>10
複製代碼
通用解法sql
在一個事務裏面, 避免一次處理太多數據數據庫
在一個事務裏面,儘可能避免沒必要要的查詢併發
在一個事務裏面, 避免耗時太多的操做,形成事務超時。一些非DB的操做,好比rpc調用,消息隊列的操做盡可能放到事務以外操做post
基於mysql5.7的解法測試
在InnoDB事務中,行鎖是在須要的時候才加上的,但並非不須要了就馬上釋放,而是要等到事務結束時才釋放。若是你的事務中須要鎖多個行,要把最可能形成鎖衝突、最可能影響併發度的鎖儘可能日後放spa
經過SETMAX_EXECUTION_TIME命令, 來控制每一個語句查詢的最長時間,避免單個語句意外查詢太長時間日誌
監控 information_schema.Innodb_trx表,設置長事務閾值,超過就報警/或者kill
在業務功能測試階段要求輸出全部的general_log,分析日誌行爲提早發現問題
設置innodb_undo_tablespaces值,將undo log分離到獨立的表空間。若是真的出現大事務致使回滾段過大,這樣設置後清理起來更方便
注:sql語句都是基於mysql5.7版本
# 查詢全部正在運行的事務及運行時間
select t.*,to_seconds(now())-to_seconds(t.trx_started) idle_time from INFORMATION_SCHEMA.INNODB_TRX t
# 查詢事務詳細信息及執行的SQL
select now(),(UNIX_TIMESTAMP(now()) - UNIX_TIMESTAMP(a.trx_started)) diff_sec,b.id,b.user,b.host,b.db,d.SQL_TEXT from information_schema.innodb_trx a inner join information_schema.PROCESSLIST b
on a.TRX_MYSQL_THREAD_ID=b.id and b.command = 'Sleep'
inner join performance_schema.threads c ON b.id = c.PROCESSLIST_ID
inner join performance_schema.events_statements_current d ON d.THREAD_ID = c.THREAD_ID;
# 查詢事務執行過的全部歷史SQL記錄
SELECT
ps.id 'PROCESS ID',
ps.USER,
ps.HOST,
esh.EVENT_ID,
trx.trx_started,
esh.event_name 'EVENT NAME',
esh.sql_text 'SQL',
ps.time
FROM
PERFORMANCE_SCHEMA.events_statements_history esh
JOIN PERFORMANCE_SCHEMA.threads th ON esh.thread_id = th.thread_id
JOIN information_schema.PROCESSLIST ps ON ps.id = th.processlist_id
LEFT JOIN information_schema.innodb_trx trx ON trx.trx_mysql_thread_id = ps.id
WHERE
trx.trx_id IS NOT NULL
AND ps.USER != 'SYSTEM_USER'
ORDER BY
esh.EVENT_ID;
# 簡單查詢事務鎖
select * from sys.innodb_lock_waits
# 查詢事務鎖詳細信息
SELECT
tmp.*,
c.SQL_Text blocking_sql_text,
p.HOST blocking_host
FROM
(
SELECT
r.trx_state wating_trx_state,
r.trx_id waiting_trx_id,
r.trx_mysql_thread_Id waiting_thread,
r.trx_query waiting_query,
b.trx_state blocking_trx_state,
b.trx_id blocking_trx_id,
b.trx_mysql_thread_id blocking_thread,
b.trx_query blocking_query
FROM
information_schema.innodb_lock_waits w
INNER JOIN information_schema.innodb_trx b ON b.trx_id = w.blocking_trx_id
INNER JOIN information_schema.innodb_trx r ON r.trx_id = w.requesting_trx_id
) tmp,
information_schema.PROCESSLIST p,
PERFORMANCE_SCHEMA.events_statements_current c,
PERFORMANCE_SCHEMA.threads t
WHERE
tmp.blocking_thread = p.id
AND t.thread_id = c.THREAD_ID
AND t.PROCESSLIST_ID = p.id
複製代碼