mysql数据库连接超时
项目最近老是在重启8小时候过后查询出错。check log,发现是mysql数据库默认wait_time时间是8小时。8小时候过后,datasource-pool中的所有连接被mysql-server端释放掉。客户端并不知道,程序直接从datasource-pool中获取连接,并没有检测连接有效性,使用的时候就出错了。
于是就趁此机会,花了两天时间仔细学习了mysql的相关设置和dbcp和c3p0。
由于要测试,肯定不能用mysql默认的8小时来测试了。等的头发都白了,还不能重现。果断重设wait_time时间。mysql 上有段原话
The number of seconds the server waits for activity on a noninteractive connection before closing it. This timeout applies only to TCP/IP and Unix socket file connections, not to connections made using named pipes, or shared memory.
这个数值只对tcp/ip和unix socket 连接有效,对命名管道,和共享内存无效。 mysql的驱动建立的连接是tcp/ip连接吧,果断继续。
然后官网上又说wait_timeout的初始值是从全局wait_timeout和 interactive_timeout.初始化来的。
果断设置全局wait_timeout。 狂百度,大家都说在my.cnf中设置,重启。好吧,my.cnf中设置好,重启mysql。show variables like '%timeout',成功了,但是测试发现没起作用。怎么一回事?百度,就那点货了,找不到。然后还是google。 原来是my.cnf设置的也是session级别的。对mysql驱动建立的连接没起作用,这里我也不明白为什么没起作用,有人知道,可以知会一声,难道mysql驱动建立的连接不是session级别么。 show gloable variables like '%timeout%'。还是默认值。也就是my.cnf设置这种方式是不成功的,直接set globle wait_timeout=10.--Query OK, 0 rows affected (0.00 sec。 怎么回事,没成功?再次show一下。原来已经成功了。 再次测试验证,wait_timeout已经设置成功。
这里为了解决问题,其实我是知道建立测试query和测试表是可以实现的。但是后来又听说连接属性设置autoReconnect=true也可以。设置过后,就像其他人一样,java的mysql驱动是不行的。autoReconnect 和autoReconnectForPool 都不行,四处查询了下。这个参数不适用java的mysql驱动。罢了,还是老老实实的设置validatequery吧。
这里项目中都引入了dbcpjar包和c3p0jar包,配置哪一种数据库连接池都可以。
dbcp: 必须设置validateQuery testOnBorrow也要设置为true。testWhileIdle设置为true也行。再次测试,其实就设置了个validateQuery也行。其他参数不要。
只是这样实际的pool中不会维持最小数量idle的连接。每次获得新的连接的时候验证连接有效性,都失效了了话,重新建立一个。
c3p0:通过idleConnectionTestPeriod和maxIdleTime 这两个参数的配置,具体就是必须小于mysq server端的wait_time时间设置,可以不用validateQuery testTable等复杂设置就解决mysql的wait_time超时的问题。
而且本人不钟爱异步程序。 c3p0不需要额外的validatquery。 不需要额外的表,保持了数据库的干净。 所以就用c3p0
使用mybatis提供的数据库连接池在同已个问题上的报错:
### Cause: org.apache.ibatis.transaction.TransactionException: Error configuring AutoCommit. Your driver may not support getAutoCommit() or setAutoCommit(). Requested setting: false. Cause: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was 238,848,846 milliseconds ago. The last packet sent successfully to the server was 238,848,847 milliseconds ago. 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.
浙公网安备 33010602011771号