昨天把一個小項目掛服務器上,測試了項目的運行是可以的。第二天打開項目,一旦打開需要使用數據庫的頁面直接就掛了。報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秒連接池會自動測試連接了。