ivaneeo's blog

自由的力量,自由的生活。

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  669 Posts :: 0 Stories :: 64 Comments :: 0 Trackbacks

之前做了一个web项目的时候,好好的网站第二天总是会提示using the Connector/J connection property 'autoReconnect=true' to avoid this problem.  这样的错误

1com.mysql.jdbc.CommunicationsException: The last packet successfully received from the server was58129 seconds ago.The last packet sent successfully to the server was 58129 seconds 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.

    问题的根本原因是是mysql超时设置的问题。如 果连接闲置8小时 (8小时内没有进行数据库操作), mysql就会自动断开连接

第一种解决方案是在 connection url中加参数: autoReconnect=true

1jdbc.url=jdbc:mysql://ipaddress:3306/database?autoReconnect=true&autoReconnectForPools=true
第二种如果使用hibernate的时候做如下配置
1<property name="connection.autoReconnect">true</property>
2<property name="connection.autoReconnectForPools">true</property>
3<property name="connection.is-connection-validation-required">true</property>
如果使用了c3p0做如下配置
1<property name="hibernate.c3p0.acquire_increment">1</property>
2<property name="hibernate.c3p0.idle_test_period">0</property>
3<property name="hibernate.c3p0.timeout">0</property>
4<property name="hibernate.c3p0.validate">true</property>
第三种方法如下:

大部分都是使用连接池方式时才会出现这个问题,短连接应该很难出现这个问题。这个问题的原因:

MySQL服务器默认的“wait_timeout”是28800秒即8小时,意味着如果一个连接的空闲时间超过8个小时,MySQL将自动断开该 连接,而连接池却认为该连接还是有效的(因为并未校验连接的有效性),当应用申请使用该连接时,就会导致上面的报错。

1.按照错误的提示,可以在JDBC URL中使用autoReconnect属性,实际测试时使用了autoReconnect=true& failOverReadOnly=false,不过并未起作用,使用的是5.1版本,可能真像网上所说的只对4之前的版本有效。

2.没办法,只能修改MySQL的参数了,wait_timeout最大为31536000即1年,在my.cnf中加入:

1wait_timeout=31536000
2 
3interactive_timeout=31536000

重启生效,需要同时修改这两个参数。

参考文档: http://aayy520.blog.163.com/blog/static/23182260201102994534777/

总结一下,这种问题主要是使用了连接池没有识别出过期的链接,解决方案就是数据库连接加一个autoReconnect的参数。或者使用框架的一些参数来控制。

posted on 2014-04-28 13:32 ivaneeo 阅读(468) 评论(0)  编辑  收藏 所属分类: java魔力

只有注册用户登录后才能发表评论。


网站导航: