MySQL 网络超时 Aborted connection db: unconnected user: root host: localhost
读超时wait_timeout 是给读请求用的,在 do_command 开始就做设置:
my_net_set_read_timeout(net, thd->variables.net_wait_timeout);
这个时候,连接是空闲的,等待用户的请求。
等读完用户的请求包后,连接就变成 active 的,在调用 dispatch_command 执行 SQL 前,通过
my_net_set_read_timeout(net, thd->variables.net_read_timeout);
把超时设置回 net_read_timeout,之后在执行 SQL 请求过程中,server 和 client 基本不会有网络交互,所以这个超时基本用不上。
有一个特殊的情况是 LOAD DATA LOCAL FILE 命令,server 在执行过程中,需要和 client 再做网络交互。
interactive_timeout 是给交互模式的客户端使用的,比如我们常用的 mysql client 工具,这个是在认证过程中设置的。
如果客户端的能力位上设置了 CLIENT_INTERACTIVE,会用 interactive_timeout 的值覆盖 wait_timeout 的值。 而一般情况下,我们应用在建立连接时,是不会设置这个能力位的。
写超时
net_write_timeout 对应写超时,在连接认证完成后,server 和 client 交互过程中写超时一真是不变的。
认证超时
connect_timeout 是给连接认证过程用的,读和写都用这个值,认证完成后,读和写分别设置为 net_read_timeout 和 net_write_timeout。
总结
可以看到和读相关的超时参数是最多的,也比较容易搞混乱。
如果是认证过程中超时,不管是读还是,都是 connect_timeout;
对于读网络超时,一般是 wait_timeout/interactive_timeout,基本不会是 net_read_timeout(特例是业务用到 LOAD DATA LOCAL FILE);
对于写网络超时,都是 net_write_timeout。
在遇到超时情况下,可以根据这些原则判断对那个参数做调整。
比如下面这种情况:
2024-05-15 19:32:41 47930 [Warning] Aborted connection 6 to db: 'unconnected' user: 'root' host: 'localhost' (Got timeout reading communication packets)
很可能需要调整的 wait_timeout/interactive_timeout。
2024-05-15 20:06:27 5063 [Warning] Aborted connection 12 to db: 'test' user: 'root' host: 'localhost' (Got timeout writing communication packets)
需要调整 net_write_timeout
需要注意的是,MySQL 的关于网络的错误,除了超时以外都认为是 error,没有做进一步的细分,比如可能会看到下面这种日志,有可能是客户端异常退出了,也有可能是网络链路异常。
2024-05-15 19:34:57 47930 [Warning] Aborted connection 8 to db: 'unconnected' user: 'root' host: 'localhost' (Got an error reading communication packets)
2024-05-15 20:07:39 5063 [Warning] Aborted connection 13 to db: 'test' user: 'root' host: 'localhost' (Got an error writing communication packets)