【Developer Log】MySQL远程连接时间长的原因和解决方式

在Java中使用JDBC连接MYSQL,当然也使用了MYSQL提供的jar包(mysql-connector-java-<version>.jar)。连接代码很简单,发现下面的情况:

1、在使用本地数据库的时候,localhost或者127.0.0.1,马上就能连上

2、在使用局域网其他机器的时候,连接时间要10秒。

当然,我自己写了一个MYSQL连接池,只需连接一次,在使用非本机数据块时,只会导致服务初始化过程加长,并不影响业务。但是这也是个很郁闷的现象,至少看着不顺眼。

经查,这是MySQL数据库在检查是否有效来源是在允许的范围内,过程中进行了反向域名翻译导致。详细参见http://dev.mysql.com/doc/refman/5.7/en/host-cache.html

The MySQL server maintains a host cache in memory that contains information about clients: IP address, host name, and error information. The server uses this cache for nonlocal TCP connections. …

For each new client connection, the server uses the client IP address to check whether the client host name is in the host cache. If not, the server attempts to resolve the host name. First, it resolves the IP address to a host name and resolves that host name back to an IP address. Then it compares the result to the original IP address to ensure that they are the same. The server stores information about the result of this operation in the host cache. If the cache is full, the least recently used entry is discarded.

根据文档的介绍,MySQL sesrver的处理流程如下:

当TCP Client连接请求时,可以获得client的IP地址。在host_cache表里面就加入一条新纪录(client ip, host name , client lookup validataion flag)。其中host name为NULL,而flag为false。

在validation flag为flas时,mysql server尝试进行ip-to-host的DNS解释,也就是进行反向DNS解析。获得后,将更新host name,并置flag为true。如果获取失败,要看是怎样错误,对于永久性错误,host name仍未NULL,而flag设置为true,如果是临时性错误,不改变(在下一个来自这个IP的client连接时,尝试再次进行解释)。

连接时间慢的根源在于mysql server对client的ip地址进行了反向DNS解析。因此有两种解决方式:

方式一:不进行反向域名翻译

如果我们只使用IP地址来确定client权限的情况,又或者DNS很慢,我们在启动mysql时(mysqld)加上 --skip-name-resolve

或者在配置文件my.cnf加上相关配置,以每次均屏蔽了方向域名解析。阿土机器my.cnf位于/etc/mysql/下,如果设置了~/.mylogin.cnf或者~/.my.cnf(名字可能和具体的mysql版本有关),则使用~/.my(login).cnf。

[mysqld]
skip-name-resolve

方式二:加快域名翻译

加快域名翻译,和localhost那样,在/etc/hosts文件中加入特定的域名解释,例如192.168.100.1  192.168.100.1;或者192.168.100.1  myproject1.company.cn。

 

相关链接:开发日志

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值