之前在公司开发的时候,突然发现系统登录不上去了,一直报超时。以前还好好的,突然就不行了,可能是因为重启数据库导致的,但也不确定。检查了很多地方,只有重启tomcat才可以。然后就开始搜资料,发现原来是mysql的连接在8个小时候会关闭,系统无法自动连接,导致操作超时。记录下处理的过程。我们使用了c3p0组件和hibernate持久化数据层。
问题信息
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was 56588 milliseconds ago.
The last packet sent successfully to the server was 56588 milliseconds ago, which
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.
大致意思是说超时了,连接不可用,给的提示可以将autoReconnect=true来避免这一问题的发生
解决方案
- 将mysql服务器的wait_timeout设置为无穷大,保证永不超时(不建议采用)像这样
- 根据提示自动重连将autoReconnect=true添加到数据库链接的代码中,像这样:
jdbc:mysql://localhost:3306/test?user=root&password=&useUnicode=true&characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false
不建议采用
3. 在mysql的wait_timeout时间之内发一次心跳,保证连接的有效性;
4. 在使用的时候检测连接的有效性,每隔一段时间就检测连接的有效性,失去就获取一个新链接
C3P0官方的建议
本文介绍一下C3P0官方推荐的方式,这种方式综合了第三和第四种解决方案
将testConnectionOnCheckout 设为 false
将testConnectionOnCheckin 设为 true
将idleConnectionTestPeriod 设为 30,这个数字要根据项目情况设定,比8小时小就好
解释一下这几个参数
testConnectionOnCheckout 设为 false
If true, an operation will be performed at every connection
checkout to verify that the connection is valid.
设置为true,所有的连接都将检测其有效性,会影响性能,所以将其设置为false;
testConnectionOnCheckin设为 true
If true, an operation will be performed asynchronously
at every connection checkin to verify that the connection is valid.
设置为true,异步检测连接的有效性
idleConnectionTestPeriod(单位是秒,不是毫秒)
If this is a number greater than 0, c3p0 will test all idle,
pooled but unchecked-out connections, every this number of seconds.
每隔多少秒c3p0检测连接的有效性
示例
注意:
在c3p0配置的时候,要注意c3p0的版本以及配置文件的格式。
<property name="hibernate.connection.provider_class">net.sf.hibernate.connection.C3P0ConnectionProvider</property>
<property name="hibernate.c3p0.max_size">30</property><!--在连接池中所有数据库连接的最大数目-->
<property name="hibernate.c3p0.min_size">5</property><!--在连接池中可用数据库连接的最小数目-->
<property name="hibernate.c3p0.timeout">120</property><!--设定数据库连接的超时时间-->
<property name="hibernate.c3p0.max_statements">100</property><!--可以被缓存的PreparedStatement的最大数目-->
<property name="hibernate.c3p0.idle_test_period">3000</property>
<property name="hibernate.c3p0.acquire_increment">2</property>
<property name="hibernate.c3p0.validate">false</property>
<!-- 连接池每隔60秒自动检测数据库连接情况,如果断开则自动重连 -->
<property name="c3p0.idleConnectionTestPeriod">60</property>
<property name="c3p0.testConnectionOnCheckout">true</property>
另一种格式
#c3p0反空闲设置,防止8小时失效问题28800
#---------------------------------------------------------
#idleConnectionTestPeriod要小于MySQL的wait_timeout
jdbc.c3p0.testConnectionOnCheckout=false
jdbc.c3p0.testConnectionOnCheckin=true
jdbc.c3p0.idleConnectionTestPeriod=3600
c3p0的简单配置就介绍这么多。