在connection的生命里,會一直有一個user thread(以及user thread對應的THD)陪伴它。
Connection和Session概念
來自Stackoverflow的一個回答:
A session is just a result of a successful connection.
Any MySQL client requires some connection settings to establish a connection,
and after the connection has been established,
it acquires a connection id (thread id) and some context which is called session.
來自官方團隊的描述:
Connections correspond to Sessions in SQL standard terminology.
A client connects to the MySQL Server and stays connected until it does a disconnect.
MySQL Client和MySQL Server建立連接的過程
Connection Phase
- Connection Requests: 是一個簡單的TCP-IP連接消息,發送到MySQL Server的端口(如:3306);
- Receiver Thread:唯一職責是創建
user thread
;要么新建一個OS thread,要么重用 thread cache里的可用thread; - User Thread: client-server protocol 處理器,比如返回
handshake packet
,接收查詢、返回結果等等;
THD
- THD: 表示connection上下文的數據結構;連接建立后被創建,斷開連接后被銷毀;
- 用戶的connection和THD是一一對應的,THD不會被connection共用;
- THD數據結構的大小約為 ~10KB,注意用來跟蹤query執行狀態各個方面;
注意:THD 一直沒查到是什么的簡寫。從查閱的資料看,THD應該也可以被認為是 Session
或者 connection的狀態/上下文
。
Command Phase
- 當connection phase一切安好后,
user thread
會進入command phase
;開始忙碌的一生。
斷開連接
Client發送COM_QUIT
命令開始斷開連接操作。
User Thread開始做清理工作:
- 釋放THD;
thread cache
還有空位置: 把自己 放到thread cache
里並標記為suspended
狀態;thread cache
沒有空位置:結束線程。
查看MySQL Sessions/Active Connections
MySQL的連接信息,記錄在information_schema
和performance_schema
數據庫中。
desc information_schema.processlist;
+---------+---------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+---------------------+------+-----+---------+-------+
| ID | bigint(21) unsigned | NO | | | |
| USER | varchar(32) | NO | | | |
| HOST | varchar(64) | NO | | | |
| DB | varchar(64) | YES | | | |
| COMMAND | varchar(16) | NO | | | |
| TIME | int(7) | NO | | | |
| STATE | varchar(64) | YES | | | |
| INFO | varchar(65535) | YES | | | |
+---------+---------------------+------+-----+---------+-------+
desc performance_schema.hosts;
+---------------------+------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------------------+------------+------+-----+---------+-------+
| HOST | char(60) | YES | UNI | NULL | |
| CURRENT_CONNECTIONS | bigint(20) | NO | | NULL | |
| TOTAL_CONNECTIONS | bigint(20) | NO | | NULL | |
+---------------------+------------+------+-----+---------+-------+
查看連接
方法1:
show status where variable_name = 'threads_connected';
方法2:
show processlist;
方法3:
select id,
user,
host,
db,
command,
time,
state,
info
from information_schema.processlist;
查看每個host的當前連接數和總連接數
select * FROM performance_schema.hosts;