视频1 视频21 视频41 视频61 视频文章1 视频文章21 视频文章41 视频文章61 推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37 推荐39 推荐41 推荐43 推荐45 推荐47 推荐49 关键词1 关键词101 关键词201 关键词301 关键词401 关键词501 关键词601 关键词701 关键词801 关键词901 关键词1001 关键词1101 关键词1201 关键词1301 关键词1401 关键词1501 关键词1601 关键词1701 关键词1801 关键词1901 视频扩展1 视频扩展6 视频扩展11 视频扩展16 文章1 文章201 文章401 文章601 文章801 文章1001 资讯1 资讯501 资讯1001 资讯1501 标签1 标签501 标签1001 关键词1 关键词501 关键词1001 关键词1501 专题2001
java调用mysql获取不到连接的问题_MySQL
2020-11-09 19:11:45 责编:小采
文档


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

com.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

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

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

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中加入:

wait_timeout=31536000
interactive_timeout=31536000

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

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

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

下载本文
显示全文
专题