mysql连接很慢,登陆到服务器上查看mysql日志:
IP address 'XX.XX.XX.XX' has been resolved to the host name 'XX.XX.XX.XX.ro.ovo.sc', which resembles IPv4-address itself.


原因是由于mysql对连接的客户端进行DNS反向解析。
有2种解决办法:
1,把client的ip写在mysql服务器的/etc/hosts文件里,随便给个名字就可以了。
2,在 my.cnf 中加入 –skip-name-resolve 。
对于第一种方法比较笨,也不实用,那么 skip-name-resolve 选项可以禁用dns解析,但是,这样不能在mysql的授权表中使用主机名了,只能使用IP。
我理解mysql是这样来处理客户端解析过程的,
1,当mysql的client连过来的时候,服务器会主动去查client的域名。
2,首先查找 /etc/hosts 文件,搜索域名和IP的对应关系。
3,如果hosts文件没有,则查找DNS设置,如果没有设置DNS服务器,会立刻返回失败,就相当于mysql设置了skip-name-resolve参数,如果设置了DNS服务器,就进行反向解析,直到timeout。



所谓反向解析是这样的:
mysql接收到连接请求后,获得的是客户端的ip,为了更好的匹配mysql.user里的权限记录(某些是用hostname定义的)。
如果mysql服务器设置了dns服务器,并且客户端ip在dns上并没有相应的hostname,那么这个过程很慢,导致连接等待。
 

添加skip-name-resolve以后就跳过着一个过程了。

官方的解释

How MySQL
uses DNS When a new thread connects to mysqld, mysqld will
spawn a new thread to handle the request. This thread will first check
if the hostname is in the hostname cache. If not the thread will call
gethostbyaddr_r() and gethostbyname_r() to resolve the hostname. If
the operating system doesn’t support the above thread-safe calls, the
thread will lock a mutex and call gethostbyaddr() and gethostbyname()
instead. Note that in this case no other thread can resolve other
hostnames that is not in the hostname cache until the first thread is
ready. You can disable DNS host lookup by starting mysqld with
–skip-name-resolve. In this case you can however only use IP names in
the MySQL privilege tables. If you have a very slow DNS and many
hosts, you can get more performance by either disabling DNS lookop
with –skip-name-resolve or by increasing the HOST_CACHE_SIZE define
(default: 128) and recompile mysqld. You can disable the hostname
cache with –skip-host-cache. You can clear the hostname cache with
FLUSH HOSTS or mysqladmin flush-hosts. If you don’t want to allow
connections over TCP/IP, you can do this by starting mysqld with
–skip-networking.

注意:在增加该配置参数后,mysql的授权表中的host字段就不能够使用域名而只能够使用 ip地址了,因为这是禁止了域名解析的结果。