mysql localhost port_MySQL 连接时尽量使用 127.0.0.1 而不是 localhost

原因

Whenever you specify "localhost" or "localhost:port" as server, the MySQL client library will override this and try to connect to a local socket (named pipe on Windows). If you want to use TCP/IP, use "127.0.0.1" instead of "localhost". If the MySQL client library tries to connect to the wrong local socket, you should set the correct path as in your PHP configuration and leave the server field blank.

localhost 使用的 Linux socket,127.0.0.1 使用的是 tcp/ip

为什么我使用 localhost 一直没出问题

因为你的本机中只有一个 mysql 进程, 如果你有一个 node1 运行在 3306, 有一个 node2 运行在 3307mysql -u root -h localhost -P 3306

mysql -u root -h localhost -P 3307

都会连接到同一个 mysql 进程, 因为 localhost 使用 Linux socket, 所以 -P 字段直接被忽略了, 等价于mysql -u root -h localhost

mysql -u root -h localhost

而 -h 默认是 localhost, 又等价于mysql -u root

mysql -u root

为了避免这种情况(比如你在本地开发只有一个 mysql 进程,线上或者 qa 环境有多个 mysql 进程)最好的方式就是使用 IPmysql -u root -h 127.0.0.1 -P 3307

使用localhost地址的stracestrace mysql -h localhost -P 3306 -u root &> /tmp/strace_mysql.txt

结果:execve("/opt/app/mysql/bin/mysql", ["mysql", "-h", "localhost", "-P", "3306", "-u", "root"], [/* 25 vars */]) = 0

......

socket(AF_LOCAL, SOCK_STREAM, 0) = 3

connect(3, {sa_family=AF_LOCAL, sun_path="/tmp/mysql.sock"}, 110) = 0 // 这里

setsockopt(3, SOL_TCP, TCP_NODELAY, [1], 4) = -1 EOPNOTSUPP (Operation not supported)

setsockopt(3, SOL_SOCKET, SO_KEEPALIVE, [1], 4) = 0

使用ip地址的stracestrace mysql -h 127.0.0.1 -P 3306 -u root &> /tmp/strace_mysql_use_ip.txt

execve("/opt/app/mysql/bin/mysql", ["mysql", "-h", "127.0.0.1", "-P", "3306", "-u", "root"], [/* 25 vars */]) = 0

....

socket(AF_INET, SOCK_STREAM, IPPROTO_TCP) = 3

connect(3, {sa_family=AF_INET, sin_port=htons(3306), sin_addr=inet_addr("127.0.0.1")}, 16) = 0

setsockopt(3, SOL_TCP, TCP_NODELAY, [1], 4) = 0

setsockopt(3, SOL_SOCKET, SO_KEEPALIVE, [1], 4) = 0

之前遇到过这个问题,但是没有找到原因,今天看到网友分享了经验,记录下

最后更新于 2020-05-29 10:56:57 并被添加「mysql」标签,已有 2045 位童鞋阅读过。

本站使用「署名 4.0 国际」创作共享协议,可自由转载、引用,但需署名作者且注明文章出处

相关文章

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值