欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

mysql连接的空闲时间超过8小时后 MySQL自动断开该连接解决方案

程序员文章站 2023-12-21 15:20:16
解决这个问题的办法有三种: 1. 增加 mysql 的 wait_timeout 属性的值。 修改 /etc/mysql/my.cnf文件,在 [mysqld] 节中设置:...
解决这个问题的办法有三种:

1. 增加 mysql 的 wait_timeout 属性的值。

修改 /etc/mysql/my.cnf文件,在 [mysqld] 节中设置:

# set a connection to wait 8hours in idle status.
wait_timeout =86400
相关参数,红色部分
mysql> show variables like '%timeout%';
+--------------------------+-------+
| variable_name | value |
+--------------------------+-------+
| connect_timeout | 5 |
| delayed_insert_timeout | 300 |
| innodb_lock_wait_timeout | 50 |
| interactive_timeout | 28800 |
| net_read_timeout | 30 |
| net_write_timeout | 60 |
| slave_net_timeout | 3600 |
| wait_timeout | 28800 |
+--------------------------+-------+
同一时间,这两个参数只有一个起作用。到底是哪个参数起作用,和用户连接时指定的连接参数相关,缺省情况下是使用wait_timeout。我建议是将这两个参数都修改,以免引起不必要的麻烦。

这两个参数的默认值是8小时(60*60*8=28800)。我测试过将这两个参数改为0,结果出人意料,系统自动将这个值设置为。换句话说,不能将该值设置为永久。
将这2个参数设置为24小时(60*60*24=604800)即可。
set interactive_timeout=604800;
set wait_timeout=604800;

2. 减少连接池内连接的生存周期,使之小于上一项中所设置的 wait_timeout 的值。
修改 c3p0 的配置文件,设置:

# how long to keep unused connections around(in seconds)
# note: mysql times out idle connections after 8hours(28,800seconds)
# so ensure this value is below mysql idle timeout
cpool.maxidletime=25200
在 spring 的配置文件中:
复制代码 代码如下:

<bean id="datasource"
class="com.mchange.v2.c3p0.combopooleddatasource">
<property name="maxidletime"value="${cpool.maxidletime}"/>
<!--other properties -->
</bean>


3. 定期使用连接池内的连接,使得它们不会因为闲置超时而被 mysql 断开。
修改 c3p0 的配置文件,设置:

# prevent mysql raise exception after a long idle timecpool.preferredtestquery='select 1'cpool.idleconnectiontestperiod=18000cpool.testconnectiononcheckout=true
修改 spring 的配置文件:
复制代码 代码如下:

<bean id="datasource" class="com.mchange.v2.c3p0.combopooleddatasource">
<property name="preferredtestquery" value="${cpool.preferredtestquery}"/>
<property name="idleconnectiontestperiod" value="${cpool.idleconnectiontestperiod}"/>
<property name="testconnectiononcheckout" value="${cpool.testconnectiononcheckout}"/>
<!--other properties --></bean>

上一篇:

下一篇: