转:Can't connect to MySQL server on 'XXXX' (10055) 解决方案

原文链接:https://blog.csdn.net/langren697/article/details/38422055

-------------------

最近做一个服务器端项目,要用到MySQL 数据库,但在大用户量并发的情况下会出现以下错误:

Can't connect to MySQL server on'localhost' (10055)

花了半天时间查找资料得以解决,现做一下总结,希望能帮到大家,有讲的不对的地方,欢迎指正,大牛勿喷。

错误的背景如下:

系统:Windows Server 2008 R2

数据库:MySql 5.5

错误现象:错误是一阵一阵的出现,一会正常,一会不正常

经过一番挣扎验证,发现将数据库放在普通的Win7 系统上不会出现该错误,所以应该可以排除这种代码层面的原因,也可以排除是MySQL 配置方面的原因。那到底是什么原因呢?经查资料得到下面这篇文章,

http://blog.whitesites.com/How-to-Fix-MySQL-Error-10055__635140180116307813_blog.htm

大家应该都能看懂,大体意思是应用程序频繁的连接访问数据库,而系统会为每个连接动态分配一个端口,Windows Server 2008 R2默认可供动态分配使用的端口只有16383 (49152 - 65535)个,(博主写成了16838,当然这是书写错误,瑕不掩瑜啊),这样的话,大并发的情况下就会导致动态端口占用完的情况,这是有人会问我的客户并发量并没有达到16383,为什么还会出现这种情况?那就涉及到端口重用问题,每个动态分配的端口号在连接关闭后,需要等待一段时间才能重新使用,这个时间是可以改变的,具体做法稍后介绍。分析到这,这个问题应该是可以解决了,具体解决办法有两个:

1. 改变可用动态端口范围

在修改之前我们可以查看一下默认到底是多少:

netsh int ipv4 show dynamicport tcp

netsh int ipv4 show dynamicport udp

netsh int ipv6 show dynamicport tcp

netsh int ipv6 show dynamicport udp

然后可以通过以下命令来配置:

netsh int <ipv4|ipv6> set dynamic <tcp|udp>start=number num=range

例如:

netsh int ipv4 set dynamicport tcp start=10000 num=50000

netsh int ipv4set dynamicport udp start=10000 num=50000

netsh int ipv6set dynamicport tcp start=10000 num=50000

netsh int ipv6set dynamicport udp start=10000 num=50000

到此或许我们就有个疑问,我么可以设置的起始端口是多少,最大可以设置多少个端口,官方说明如下:

The minimum range of ports that can be set is 255. Theminimum starting port that can be set is 1025. The maximum end port (based onthe range being configured) cannot exceed 65535。

也就是说 start的最小值是1025,num指的是范围,最小值是255,最大值及start + num < 65535.

官方原文链接地址:

http://support.microsoft.com/kb/929851/en-us

有时候可能需要配置动态端口最大值:

因为官方如下描述:

If youtry to set up TCP connections from ports that are greater than 5000, the localcomputer responds with the following WSAENOBUFS (10055) error message:

An operation on a socket could not be performed because thesystem lacked sufficient buffer space or because a queue was full.

就是说当TCP链接大于5000时,就会报10055错误。

通过注册表配置动态分配端口的最大值:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters里加上如下的键值:

ValueName: MaxUserPort

ValueType: DWORD

Valuedata: 65534

ValidRange: 5000-65534 (decimal)

Default:0x1388 (5000 decimal)

官方原文链接地址:

http://support.microsoft.com/kb/196271/en-us

2. 设置端口复用时间:

可以通过修改或添加如下注册表字段来配置:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters加上

键值:TcpTimedWaitDelay

数值类型:REG_DWORD - 时间(以秒为单位)

有效范围:30-300(十进制)

默认值:0x78(十进制 120)

描述:此参数确定连接在关闭时保持 TIME_WAIT 状态的时长。只要连接处于 TIME_WAIT 状态,便不能重新使用套接字对。

为了复用的快一些:可以设置为最小值:30

官方文档:

http://support.microsoft.com/kb/314053 

原文地址:https://www.cnblogs.com/qima/p/15809210.html