数据库连接太多

数据库连接太多

1 show processlist

可以通过show processlist来查看当前的mysql连接,处于sleep状态的线程正在等待客户端发送新的请求,处于空闲状态,可以通过kill命令关闭这些线程,释放数据库连接。

2 max_connections

可以增加全局变量max_connections,mysql允许的最大用户连接数,设置此值的一个参考方法是查看全局状态变量Max_used_connections,数据库过去的最大连接数,一般数据库的最大连接数应该占到数据库允许的最大连接数的10%以上。

3 wait_timeout

另外一个可以调整的参数是wait_timeout,数据库断开一个非交互式连接前所要等待的秒数,这个值过大了会造成MySQL里面大量的sleep线程无法释放。但是过小了也不好,可能会遇到MySQL has gone away之类的问题。

对于wait_timeout的值设定,应该根据系统的运行情况来判断。在系统运行一段时间后,可以通过show processlist命令查看当前系统的连接状态,如果发现有大量的sleep状态的连接进程,则说明该参数设置的过大,可以进行适当的调整小些。

4 c3p0 的 idleConnectionTestPeriodtestConnectionOnCheckin

另外设置了wait_timeout后,使用 c3p0 数据源的 Spring 后端有可能会报如下错误:

The last packet sent successfully to the server was 55,518,631 milliseconds ago. is longer than the server configured value of ‘wait_timeout’. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property ‘autoReconnect=true’ to avoid this problem.;

很明显是由于后端请求获取数据库连接时,该连接的空闲时间超过了wait_timeout设定的值已经被数据库关闭。

解决方案上面的英文也已经给出,可以考虑在应用端设置连接超时时间或者检测连接的有效性;或者增加数据库服务器的超时时间;或者设置连接器的autoReconnect属性为true。

后面两种方案并不优秀,数据库的wait_timeout不宜过长,否则可能空闲连接会很多;而autoReconnect属性使用的时候 reconnect 会影响效率,而且据说mysql5以上无效(本人没试)

推荐使用的是c3p0的解决方案:

The most reliable time to test Connections is on check-out. But this is also the most costly choice from a client-performance perspective. Most applications should work quite reliably using a combination of idleConnectionTestPeriod and testConnectionOnCheckin. Both the idle test and the check-in test are performed asynchronously, which can lead to better performance, both perceived and actual.
For some applications, high performance is more important than the risk of an occasional database exception. In its default configuration, c3p0 does no Connection testing at all. Setting a fairly long idleConnectionTestPeriod, and not testing on checkout and check-in at all is an excellent, high-performance approach.

使用idleConnectionTestPeriodtestConnectionOnCheckin分别来设置检测c3p0连接池内空闲连接的时间以及在取得连接的同时是否校验连接的有效性。两者异步进行,可以提供较好的性能。在需要高性能的应用中,c3p0可以不检测连接。

一般把c3p0中连接池内连接的生存周期的idleConnectionTestPeriod 设置为比数据库的 wait_timeout 小比较好,防止获取到的数据库连接是无效的。

参考资料

[1] https://www.jb51.net/article/93921.htm C3P0连接池+MySQL的配置及wait_timeout问题的解决方法

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值