<!--當連接池中的連接耗盡的時候 c3p0 一次同時獲取的連接數。Default: 3 --> <propert name="acquireRetryAttempts">30</property>
<!--兩次連接中間隔時間,單位毫秒。Default: 1000 --> <property name="acquireRetryDelay">1000</property>
<!--連接關閉時默認將所有未提交的操作回滾。Default: false --> <property name="autoCommitOnClose">false</property>
<!--c3p0 將建一張名為 Test 的空表,並使用其自帶的查詢語句進行測試。如果 定義了這個參數那么 屬性 preferredTestQuery 將被忽略。你不能在這張 Test 表上進行任何操作,它 將只供 c3p0 測試 使用。Default: null--> <property name="automaticTestTable">Test</property>
<!--獲取連接失敗將會引起所有等待連接池來獲取連接的線程拋出異常。 但是數 據源仍有效 保留, 並在下次調用 getConnection()的時候繼續嘗試獲取連接。 如果設為 true, 那么在嘗試 獲取連接失敗后該數據源將申明已斷開並永久關閉。Default: false--> <property name="breakAfterAcquireFailure">false</property>
<!--當連接池用完時客戶端調用 getConnection()后等待獲取新連接的時間,超 時后將拋出 SQLException,如設為 0 則無限期等待。單位毫秒。Default: 0 --> <property name="checkoutTimeout">100</property>
<!--通過實現 ConnectionTester 或 QueryConnectionTester 的類來測試連接。 類名需制定全路徑。 Default: com.mchange.v2.c3p0.impl.DefaultConnectionTester--> <property name="connectionTesterClassName"></property>
<!--指定 c3p0 libraries 的路徑,如果(通常都是這樣)在本地即可獲得那么 無需設置,默認 null 即可 Default: null--> <property name="factoryClassLocation">null</property>
<!--Strongly disrecommended. Setting this to true may lead to subtle and bizarre bugs. (文檔原文)作者強烈建議不使用的一個屬性--> <property name="forceIgnoreUnresolvedTransactions">false</property>
<!--每 60 秒檢查所有連接池中的空閑連接。Default: 0 --> <property name="idleConnectionTestPeriod">60</property>
<!--初始化時獲取三個連接,取值應在 minPoolSize 與 maxPoolSize 之間。 Default: 3 --> <property name="initialPoolSize">3</property>
<!--最大空閑時間,60 秒內未使用則連接被丟棄。若為 0 則永不丟棄。Default: 0 --> <property name="maxIdleTime">60</property>
<!--連接池中保留的最大連接數。Default: 15 --> <property name="maxPoolSize">15</property>
<!--JDBC 的標准參數,用以控制數據源內加載的 PreparedStatements 數量。但 由於預緩存的 statements 屬於單個 connection 而不是整個連接池。所以設置這個參數需要考慮到多方面 的因素。 如果 maxStatements 與 maxStatementsPerConnection 均為 0,則緩存被關閉。 Default: 0--> <property name="maxStatements">100</property>
<!--maxStatementsPerConnection 定義了連接池內單個連接所擁有的最大緩存 statements 數。Default: 0 --> <property name="maxStatementsPerConnection"></property>
<!--c3p0 是異步操作的,緩慢的 JDBC 操作通過幫助進程完成。擴展這些操作可 以有效的提升性能 通過多線程實現多個操作同時被執行。Default: 3--> <property name="numHelperThreads">3</property>
<!--當用戶調用 getConnection()時使 root 用戶成為去獲取連接的用戶。主要 用於連接池連接非 c3p0 的數據源時。Default: null--> <property name="overrideDefaultUser">root</property>
<!--與 overrideDefaultUser 參數對應使用的一個參數。Default: null--> <property name="overrideDefaultPassword">password</property>
<!--密碼。Default: null--> <property name="password"></property>
<!--定義所有連接測試都執行的測試語句。 在使用連接測試的情況下這個一顯著 提高測試速度。注意: 測試的表必須在初始數據源的時候就存在。Default: null--> <property name="preferredTestQuery">select id from test where id=1</property>
<!--用戶修改系統配置參數執行前最多等待 300 秒。Default: 300 --> <property name="propertyCycle">300</property>
<!--因性能消耗大請只在需要的時候使用它。如果設為 true 那么在每個 connection 提交的 時候都將校驗其有效性。建議使用 idleConnectionTestPeriod 或 automaticTestTable 等方法來提升連接測試的性能。Default: false --> <property name="testConnectionOnCheckout">false</property>
<!--如果設為 true 那么在取得連接的同時將校驗連接的有效性。 Default: false --> <property name="testConnectionOnCheckin">true</property>
<!--用戶名。Default: null--> <property name="user">root</property>
<!--早期的 c3p0 版本對 JDBC 接口采用動態反射代理。 在早期版本用途廣泛的情 況下這個參數 允許用戶恢復到動態反射代理以解決不穩定的故障。 最新的非反射代理更快並且 已經開始 廣泛的被使用, 所以這個參數未必有用。現在原先的動態反射與新的非反射代理 同時受到 支持,但今后可能的版本可能不支持動態反射代理。Default: false--> <property name="usesTraditionalReflectiveProxies">false</property>
<!--當連接池用完時客戶端調用 getConnection()后等待獲取新連接的時間, 超時 SQLException,如設為 0 則無限期等待。單位毫秒。Default: 0 --> <property name="checkoutTimeout">100</property>
<!--c3p0 將建一張名為 Test 的空表,並使用其自帶的查詢語句進行測試。如果 定義了這個參數那么屬性 preferredTestQuery 將被忽略。 你不能在這張 Test 表上進行任何操作, 它將 只供 c3p0 測試使用。Default: null--> <property name="automaticTestTable">Test</property>
<!--JDBC 的標准參數,用以控制數據源內加載的 PreparedStatements 數量。但 由於預緩存的 statements屬於單個 connection 而不是整個連接池。所以設置這個參數需要考慮到多方面 的因素。如果 maxStatements 與 maxStatementsPerConnection 均為 0,則緩存被關閉。 Default: 0--><property name="maxStatements">100</property>
<!--maxStatementsPerConnection 定義了連接池內單個連接所擁有的最大緩存 statements 數。Default: 0 --> <property name="maxStatementsPerConnection"></property>
<!--c3p0 是異步操作的,緩慢的 JDBC 操作通過幫助進程完成。擴展這些操作 可以有效的提升性能 通過多線程實現多個操作同時被執行。Default: 3--><property name="numHelperThreads">3</property>
<!--用戶修改系統配置參數執行前最多等待 300 秒。Default: 300 --> <property name="propertyCycle">300</property>
解決 MYSQL 8 小時問題 最近的一個項目在 Hibernate 使用 C3P0 的連接池,數據庫為 Mysql。開發測試 沒有問題,在運行中每個一段長的空閑時間就出現異常: java 代碼 1. org.hibernate.exception.JDBCConnectionException: could not execute query 2. at org.hibernate.exception.SQLStateConverter.convert(SQLStateConve rter.java:74) 3. at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExcepti onHelper.java:43) 4. ....... 5. Caused by: com.mysql.jdbc.exceptions.MySQLNonTransientConnectionException: No operations allowed after connection closed.Connection was implicitly closed due to underlying exception/error: 6. ** BEGIN NESTED EXCEPTION ** 7. com.mysql.jdbc.CommunicationsException 8. MESSAGE: Communications link failure due to underlying exception: 9. ** BEGIN NESTED EXCEPTION ** 10.java.net.SocketException 11.MESSAGE: Broken pipe 12.STACKTRACE: 13.java.net.SocketException: Broken pipe 14.at java.net.SocketOutputStream.socketWrite0(Native Method) 15....... 16.** END NESTED EXCEPTION **
查看了 Mysql 的文檔, 以及 Connector/J 的文檔以及在線說明發現,出現這種異 常的原因是: Mysql 服務器默認的“wait_timeout”是 8 小時,也就是說一個 connection 空 閑超過 8 個小時, Mysql 將自動斷開該 connection。 這就是問題的所在, 在 C3P0 pools 中的 connections 如果空閑超過 8 小時,Mysql 將其斷開,而 C3P0 並不知 道該 connection 已經失效,如果這時有 Client 請求 connection,C3P0 將該失 效的 Connection 提供給 Client,將會造成上面的異常。 解決的方法有 3 種: 1. 增加 wait_timeout 的時間。 2. 減少 Connection pools 中 connection 的 lifetime。 3. 測試 Connection pools 中 connection 的有效性。 當然最好的辦法是同時綜合使用上述 3 種方法, 下面就 DBCP 和 C3P0 分別做一說 明,假設 wait_timeout 為默認的 8 小時 DBCP 增加以下配置信息: 1. //set to 'SELECT 1' 2. validationQuery = "SELECT 1" 3. //set to 'true' 4. testWhileIdle = "true" 5. //some positive integer 6. timeBetweenEvictionRunsMillis = 3600000 7. //set to something smaller than 'wait_timeout' 8. minEvictableIdleTimeMillis = 18000000 9. //if you don't mind a hit for every getConnection(), set to "true" 10.testOnBorrow = "true" C3P0 增加以下配置信息: 1. 2. 3. 4. 5. //獲取 connnection 時測試是否有效 testConnectionOnCheckin = true //自動測試的 table 名稱 automaticTestTable=C3P0TestTable //set to something much less than wait_timeout, prevents connections from going stale 6. idleConnectionTestPeriod = 18000 7. //set to something slightly less than wait_timeout, preventing 'stale' connections from being handed out 8. maxIdleTime = 25000 9. //if you can take the performance 'hit', set to "true" 10.testConnectionOnCheckout = true
//初始化時獲取三個連接,取值應在 minPoolSize 與 maxPoolSize 之間。Default: 3 initialPoolSize ds.setInitialPoolSize(3);
//連接池中保留的最大連接數。Default: 15 maxPoolSize ds.setMaxPoolSize(10);
// 連接池中保留的最小連接數。 //ds.setMinPoolSize(1);
//當連接池中的連接耗盡的時候 c3p0 一次同時獲取的連接數。Default: 3 acquireIncrement ds.setAcquireIncrement(1);
//每 60 秒檢查所有連接池中的空閑連接。Default: 0 idleConnectionTestPeriod ds.setIdleConnectionTestPeriod(60);
//最大空閑時間,25000 秒內未使用則連接被丟棄。若為 0 則永不丟棄。Default: 0 maxIdleTime ds.setMaxIdleTime(25000);
//連接關閉時默認將所有未提交的操作回滾。Default: false autoCommitOnClose ds.setAutoCommitOnClose(true);
//定義所有連接測試都執行的測試語句。在使用連接測試的情況下這個一顯著提高測試速度。注意:測試的表必須在初始數據源的時候就存在。Default: null preferredTestQuery ds.setPreferredTestQuery("select sysdate from dual");
// 因性能消耗大請只在需要的時候使用它。如果設為 true 那么在每個 connection 提交 的時候都將校驗其有效性。建議使用 idleConnectionTestPeriod 或 automaticTestTable等方法來提升連接測試的性能。Default: false testConnectionOnCheckout ds.setTestConnectionOnCheckout(true);
//如果設為 true 那么在取得連接的同時將校驗連接的有效性。Default: false testConnectionOnCheckin ds.setTestConnectionOnCheckin(true);
//定義在從數據庫獲取新連接失敗后重復嘗試的次數。Default: 30 acquireRetryAttempts ds.setAcquireRetryAttempts(30);
//兩次連接中間隔時間,單位毫秒。Default: 1000 acquireRetryDelay ds.setAcquireRetryDelay(1000);
//獲取連接失敗將會引起所有等待連接池來獲取連接的線程拋出異常。但是數據源仍 有效保留,並在下次調用 getConnection()的時候繼續嘗試獲取連接。如果設為 true,那么 在嘗試獲取連接失敗后該數據源將申明已斷開並永久關閉。Default: false breakAfterAcquireFailure ds.setBreakAfterAcquireFailure(true);
Java配置c3p0
import java.sql.Connection;
import java.sql.SQLException;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.mchange.v2.c3p0.DataSources;
public final class ConnectionManager {
private static ConnectionManager instance;
private ComboPooledDataSource ds;
private ConnectionManager() throws Exception {
ds = new ComboPooledDataSource();
ds.setDriverClass("oracle.jdbc.driver.OracleDriver");
ds.setJdbcUrl("jdbc:oracle:thin:@127.0.0.1:1521:orcl");
ds.setUser("test"); ds.setPassword("testtest");}
public static final ConnectionManager getInstance() {
if (instance == null) {
try { instance = new ConnectionManager();} catch (Exception e) { e.printStackTrace(); }
} return instance;
}
public synchronized final Connection getConnection() {
try { return ds.getConnection(); } catch (SQLException e) { e.printStackTrace();} return null;
}
protected void finalize() throws Throwable { DataSources.destroy(ds); //關閉 datasource super.finalize(); }
} //調用數據庫連接池
import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement;
public class TestC3p0 {
public TestC3p0() { // TODO 自動生成構造函數存根 }
public static void main(String[] args) { // TODO 自動生成方法存根
ConnectionManager cm = ConnectionManager.getInstance();
Connection conn = null; Statement stmt = null; ResultSet rs = null; String sql = "select sysdate from dual";
for (int i = 0; i < 10000; i++) {
try { conn = cm.getConnection(); System.out.println(conn); stmt = conn.createStatement(); rs = stmt.executeQuery(sql); rs.next(); System.out.println(rs.getString(1)); } catch (Exception ex) { ex.printStackTrace(); } finally {
if (rs != null) { try { rs.close(); } catch (Exception e) { } }
if (stmt != null) { try { stmt.close(); } catch (Exception e) { } }
if (conn != null) { try { conn.close(); } catch (Exception e) { } } }
try { System.out.println(cm.ds.toString()); Thread.sleep(10000); } catch (Exception e) { // TODO: handle exception } }
}
}
此文為網絡轉載