解决C3P0连接MySQL链接失效的问题

  昨天把一个小项目挂服务器上,测试了项目的运行是可以的。第二天打开项目,一旦打开需要使用数据库的页面直接就挂了。报JDBC EXCEPTION,还提示去修改一个wait_timeout的字段。网上搜了下,这个wait_timeout是管理MySQL链接有效期的变量,可以通过以下语句查出MySQL链接的超时时间。

  

  此处wait_timeout是28800秒,也就是8个小时。

  C3P0作为连接池,它的最大的任务就是来管理链接的,可是实际上它并不知道这个链接是否还有效,所以,当MySQL某个链接的建立时间已经超过了wait_timeout的时候,那么这个链接实际上已经不能用了。而C3P0却还不知道,相当于C3P0持有了不能使用的链接。

  那么解决这个问题也就有两个思路了。

  1.延长MySQL的wait_timeout

  2.让C3P0主动去测试持有的链接是否有效

  考虑到实际中的应用,第一种思路其实并不是很好,因为C3P0作为连接池,理所应当地管理一切跟链接有关的东西,所以,从第二种思路入手比较合适些。

  关于链接失效的问题,C3P0官方文档给出了这样子的解决方式

  

Begin by setting testConnectionOnCheckout to true and get your application to run correctly and stably. If you are happy with your application's performance, you can stop here! This is the simplest, most reliable form of Connection-testing, but it does have a client-visible performance cost.

If you'd like to improve performance by eliminating Connection testing from clients' code path:

Set testConnectionOnCheckout to false

Set testConnectionOnCheckin to true

Set idleConnectionTestPeriod to 30, fire up you application and observe. This is a pretty robust setting, all Connections will tested on check-in and every 30 seconds thereafter while in the pool. Your application should experience broken or stale Connections only very rarely, and the pool should recover from a database shutdown and restart quickly. But there is some overhead associated with all that Connection testing.

  简单点概括,在配置C3P0的时候,如果要防止链接失效的情况,可以配置一个testConnectionOnCheckout的属性,当时该属性会比较大的影响性能。

  如果比较在意性能的,可以设置testConnectionOnCheckout为false,设置testConnectionOnCheckin为true,设置idleConnectionTestPeriod为30秒

  spring中配置数据源

  

  properties文件

  

   

  启动项目,通过输出日志可看到,每30秒连接池会自动测试连接了。

  

posted @ 2017-10-08 15:53  小佘Blog  阅读(2208)  评论(0编辑  收藏  举报