2

What is the standard approach in Java to test whether a MySQL connection has been timed out by the server / keep the conneciton alive? (com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was 73.596.145 milliseconds ago ...)

Some articles recommended periodic pinging to keep the connection alive. I could start a separated thread which does this, ok. However, is there some easy test that I could perform and reconnect only if necessary? Or is periodic pinging the best-performance way to go here?

boolean java.sql.Connection.isClosed() states "This method is guaranteed to return true only when it is called after the method Connection.close has been called" and I guess that this will not do the job for me.

I could internally keep track of seconds since last request, compare that to select @@wait_timeout; and reconnect if too much time has passed.

So, what is the standard approach to know if the connection has timed out / keep the connection alive?

Thanks a lot in advance!

4

1 回答 1

1

我遇到了同样的问题。

必须测试的解决方案是从 java.sql.Connection 调用“isValid(int timeout)”方法

或者在mysql中设置自动重连:http: //dev.mysql.com/doc/refman/5.0/en/auto-reconnect.html

或更改 mysql 中的超时时间(默认 = 8 小时):http ://dev.mysql.com/doc/refman/5.0/en/server-system-variables.html#sysvar_wait_timeout

编辑:但我认为最好的做法是在事务期间打开连接,然后直接关闭它。

于 2013-09-24T14:10:31.180 回答