您好,登錄后才能下訂單哦!
這篇文章主要介紹“Hibernate如何使用C3P0的連接池”,在日常操作中,相信很多人在Hibernate如何使用C3P0的連接池問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”Hibernate如何使用C3P0的連接池”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!
最近的一個(gè)項(xiàng)目在Hibernate使用C3P0的連接池,數(shù)據(jù)庫為Mysql。開發(fā)測試沒有問題,在運(yùn)行中每個(gè)一段長的空閑時(shí)間就出現(xiàn)異常:[@more@]最近的一個(gè)項(xiàng)目在Hibernate使用C3P0的連接池,數(shù)據(jù)庫為Mysql。開發(fā)測試沒有問題,在運(yùn)行中每個(gè)一段長的空閑時(shí)間就出現(xiàn)異常:
java 代碼
org.hibernate.exception.JDBCConnectionException: could not execute query
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:74)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
.......
Caused by: com.mysql.jdbc.exceptions.MySQLNonTransientConnectionException: No operations allowed after connection closed.Connection was implicitly closed due to underlying exception/error:
** BEGIN NESTED EXCEPTION **
com.mysql.jdbc.CommunicationsException
MESSAGE: Communications link failure due to underlying exception:
** BEGIN NESTED EXCEPTION **
java.net.SocketException
MESSAGE: Broken pipe
STACKTRACE:
java.net.SocketException: Broken pipe
at java.net.SocketOutputStream.socketWrite0(Native Method)
......
** END NESTED EXCEPTION **
查看了Mysql的文檔,以及Connector/J的文檔以及在線說明發(fā)現(xiàn),出現(xiàn)這種異常的原因是:
Mysql服務(wù)器默認(rèn)的“wait_timeout”是8小時(shí),也就是說一個(gè)connection空閑超過8個(gè)小時(shí),Mysql將自動(dòng)斷開該connection。這就是問題的所在,在C3P0 pools中的connections如果空閑超過8小時(shí),Mysql將其斷開,而C3P0并不知道該connection已經(jīng)失效,如果這時(shí)有Client請求connection,C3P0將該失效的Connection提供給Client,將會(huì)造成上面的異常。
解決的方法有3種:
增加wait_timeout的時(shí)間。
減少Connection pools中connection的lifetime。
測試Connection pools中connection的有效性。
當(dāng)然最好的辦法是同時(shí)綜合使用上述3種方法,下面就DBCP和C3P0分別做一說明,假設(shè)wait_timeout為默認(rèn)的8小時(shí)
DBCP增加以下配置信息:
//set to 'SELECT 1'
validationQuery = "SELECT 1"
//set to 'true'
testWhileIdle = "true"
//some positive integer
timeBetweenEvictionRunsMillis = 3600000
//set to something smaller than 'wait_timeout'
minEvictableIdleTimeMillis = 18000000
//if you don't mind a hit for every getConnection(), set to "true"
testOnBorrow = "true"
C3P0增加以下配置信息:
//set to 'SELECT 1'
preferredTestQuery = 'SELECT 1'
//set to something much less than wait_timeout, prevents connections from going stale
idleConnectionTestPeriod = 18000
//set to something slightly less than wait_timeout, preventing 'stale' connections from being handed out
maxIdleTime = 25000
//if you can take the performance 'hit', set to "true"
testConnectionOnCheckout = true
更多的配置信息大家可以查看C3P0文檔,Connector/J文檔,以及DBCP的文檔。
到此,關(guān)于“Hibernate如何使用C3P0的連接池”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。