JDBC实现Mysql自动重连机制的方法详解
前言
本文主要给大家介绍的是关于JDBC实现Mysql自动重连机制的相关内容,分享出来供大家参考学习,下面来一起看看详细的介绍:
日志: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就会自动断开连接, 要重启tomcat.
解决办法:
第一种:如果不用hibernate的话, 则在 connection url中加参数: autoReconnect=true
jdbc.url=jdbc:mysql://ipaddress:3306/database?autoReconnect=true&autoReconnectForPools=true
第二种:用hibernate的话, 加如下属性:
<property name="connection.autoReconnect">true</property> <property name="connection.autoReconnectForPools">true</property> <property name="connection.is-connection-validation-required">true</property>
第三种:要是还用c3p0连接池:
<property name="hibernate.c3p0.acquire_increment">1</property> <property name="hibernate.c3p0.idle_test_period">0</property> <property name="hibernate.c3p0.timeout">0</property> <property name="hibernate.c3p0.validate">true</property>
第四种:最不好的解决方案
使用Connector/J连接MySQL数据库,程序运行较长时间后就会报以下错误:
Communications link failure,The last packet successfully received from the server was *** millisecond ago.The last packet successfully sent to the server was *** millisecond ago。
其中错误还会提示你修改wait_timeout或是使用Connector/J的autoReconnect属性避免该错误。
后来查了一些资料,才发现遇到这个问题的人还真不少,大部分都是使用连接池方式时才会出现这个问题,短连接应该很难出现这个问题。
这个问题的原因:
MySQL服务器默认的“wait_timeout”是28800秒即8小时,意味着如果一个连接的空闲时间超过8个小时,MySQL将自动断开该 连接,而连接池却认为该连接还是有效的(因为并未校验连接的有效性),当应用申请使用该连接时,就会导致上面的报错。
⑴.按照错误的提示,可以在JDBC URL中使用autoReconnect属性,实际测试时使用了
autoReconnect=true& failOverReadOnly=false,不过并未起作用,使用的是5.1版本,可能真像网上所说的只对4之前的版本有效。
⑵.没办法,只能修改MySQL的参数了,wait_timeout最大为31536000即1年,在my.cnf中加入:
[mysqld] wait_timeout=31536000 interactive_timeout=31536000
重启生效,需要同时修改这两个参数。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对脚本之家的支持。
您可能感兴趣的文章:
- JDBC如何实现Mysql自动重连的机制
- JDBC如何实现Mysql自动重连的机制
- Javascript学习之H5自动重连技术实现方法详解
- PHP基于反射机制实现自动依赖注入的方法详解
- MYSQL JDBC快速查询响应的方法,快速返回机制的实现
- JAVAWEB开发之事务详解(mysql与JDBC下使用方法、事务的特性、锁机制)和连接池的详细使用(dbcp以c3p0)
- ViewPager实现循环滑动实现方法+定时自动滑动实现方法详解
- 详解两种C#自动实现DLL(OCX)控件注册的方法
- Reactor和Proactor模式下带有自动重连机制的客户端实现
- MySql实现跨表查询的方法详解
- PHP连接MySql闪断自动重连的方法
- mysql 连接闪断自动重连的方法
- Mysql自动备份实现方法
- PHP连接MySql闪断自动重连的方法
- Navicat异地自动备份MySQL方法详解(图文)
- elasticsearch-jdbc实现MySQL同步到ElasticSearch深入详解
- delphi WebBrowser的使用方法详解(四)-webbrowser轻松实现自动填表
- mysql 分表实现方法详解
- 基于JavaScript实现继承机制之调用call()与apply()的方法详解
- android-servlet-mysql servlet代码实现用户登陆 (结合上一篇jdbc封装里面的方法)