我目前使用的是 tomcat 6 和 MySQL 5.1.56。 它使用 Mysql Connector-j 获取数据库连接并使用它们。 我已经按照此链接设置了一个连接池。
http://people.apache.org/~fhanik/tomcat/jdbc-pool.html
只要我在使用它,一切都很好。
如果我让它闲置几个小时,那么我将无法执行任何查询。 我得到以下异常。
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: **No operations allowed after connection closed.**
java.lang.RuntimeException: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed.
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: **Communications link failure**
The last packet successfully received from the server was 31,858,914 milliseconds ago. The last packet sent successfully to the server was 11 milliseconds ago.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1116)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3090)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2979)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3520)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1990)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2151)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2625)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2119)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2281)
我看到堆栈上的另一个人溢出了同样的问题但没有回答。 Database Connections Timing Out (Connection Pooling On Tomcat)
我在这里找到了一个解决方案,但我无法使用它,因为它指示我使用另一个我无权使用的第三方应用程序。
https://groups.google.com/group/ctjug-forum/browse_thread/thread/c326d3595d0c91af
有什么方法可以解决这个问题,而无需部署第三方 jar/应用程序。
我已经尝试过自动重新连接、访问连接前后测试连接等选项以及所有其他选项。
这是我当前在 conext.xml 中的设置
<Resource name="jdbc/appdb" auth="Container"
type="javax.sql.DataSource"
username="**********"
password="**********"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/appdb?autoReconnect=true"
maxActive="15" maxIdle="3"
testWhileIdle="true"
testOnBorrow="true"
testOnReturn="false"
validationQuery="SELECT 1"
validationInterval="30000"
timeBetweenEvictionRunsMillis="30000"/>
在这种情况下,最佳实践解决方案是什么?
我在 mysql 日志中找不到任何内容。
最佳答案
你不应该让任何连接打开几个小时。
你应该有一个持久层,它从池中获取连接,执行操作,提交或回滚,并关闭连接以将其返回到尽可能小的范围内的池中。如果您不将自己限制在每个 session 一个连接,您的应用程序将更具可扩展性。您的应用程序将具有足够的响应能力,因为池将分摊为您的所有请求打开每个连接的成本。
有些池的配置允许您在将连接从池中取出之前检查连接,并在连接过时时提供新的连接。查看如何使用您的池/应用程序服务器执行此操作。
关于java - 连接池中的 Tomcat-Mysql 连接在空闲时间后超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9750781/