首页 > 代码库 > C3P0连接池配置

C3P0连接池配置

  C3P0是一个开源的JDBC连接池,它实现了数据源和JNDI绑定,支持JDBC3规范和JDBC2的标准扩展。目前使用它的开源项目Hibernate,Spring等。

闲来无事,学习了一下C3P0的配置和使用,特此把一些步骤和出现的问题记录一下:

1、JdbcUtils.java

 1 /** 2  * 使用本类的方法,必须提供c3p0-copnfig.xml文件 3  *  4  * @author C 5  */ 6 public class JdbcUtils { 7     // 饿汉式 8     private static DataSource ds = new ComboPooledDataSource(); 9     /**10      * 它为null表示没有事务 11      * 它不为null表示有事务 12      * 当开启事务时,需要给它赋值 13      * 当结束事务时,需要给它赋值为null14      * 并且在开启事务时,让dao的多个方法共享这个Connection15      */16     private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();17 18     public static DataSource getDataSource() {19         return ds;20     }21     /**22      * dao使用本方法来获取连接23      * 24      * @return25      * @throws SQLException26      */27     public static Connection getConnection() throws SQLException {28         /*29          * 如果有事务,返回当前事务的con 如果没有事务,通过连接池返回新的con30          */31         Connection con = tl.get();// 获取当前线程的事务连接32         if (con != null) {33             return con;34         }35         return ds.getConnection();36     }37 38     /**39      * 开启事务40      * @throws SQLException 41      */42     public static void beginTransaction() throws SQLException {43         Connection con = tl.get();//获取当前线程的事务连接44         if (con != null) {45             throw new SQLException("已经开启了事务,不能重复开启!");46         } 47         con = ds.getConnection();//给con赋值,表示开启了事务48         con.setAutoCommit(false);//设置为手动提交49         tl.set(con);////把当前事务连接放到tl中50     }51     52     /**53      * 提交事务54      * @throws SQLException 55      */56     public static void commitTransaction() throws SQLException {57         Connection con = tl.get();//获取当前线程的事务连接58         if(con == null) throw new SQLException("没有事务不能提交!");59         con.commit();//提交事务60         con.close();//关闭连接61         con = null;//表示事务结束!62         tl.remove();63     }64     65     /**66      * 释放Connection67      * @param con68      * @throws SQLException 69      */70     public static void releaseConnection(Connection connection) throws SQLException {71         Connection con = tl.get();//获取当前线程的事务连接72         if(connection != con) {//如果参数连接,与当前事务连接不同,说明这个连接不是当前事务,可以关闭!73             if(connection != null &&!connection.isClosed()) {//如果参数连接没有关闭,关闭之!74                 connection.close();75             }76         }77     }78 }

2、c3p0-copnfig.xml

 1 <?xml version="1.0" encoding="UTF-8" ?> 2 <c3p0-config> 3     <default-config>  4         <property name="jdbcUrl"> 5                 jdbc:mysql://localhost:3306/cms 6         </property> 7         <property name="driverClass">com.mysql.jdbc.Driver</property> 8         <property name="user">root</property> 9         <property name="password">root</property>10         11         <property name="acquireIncrement">3</property>12         <property name="initialPoolSize">10</property>13         <property name="minPoolSize">2</property>14         <property name="maxPoolSize">10</property>15     </default-config>16 </c3p0-config>

3、需要导入的jar包

  c3p0.jar   mysql-connector.jar  mchange-commons-0.2.jar

问题1:如果不加入mchange-commons-0.2.jar,会出现以下问题:

    Caused by: java.lang.NoClassDefFoundError: com/mchange/v2/ser/Indirector

4、进行单元测试(导入junit4库)

JdbcUtilsTest.java

1 public class JdbcUtilTest {2     3     @Test4     public void jdbcUtils() throws SQLException {5         Connection con = JdbcUtils.getConnection();6         System.out.println(con);7     }8 }

控制台输出以下内容:

1 2014-8-13 9:17:30 com.mchange.v2.log.MLog <clinit>2 信息: MLog clients using java 1.4+ standard logging.3 2014-8-13 9:17:30 com.mchange.v2.c3p0.C3P0Registry banner4 信息: Initializing c3p0-0.9.2-pre1 [built 27-May-2010 01:00:49 -0400; debug? true; trace: 10]5 2014-8-13 9:17:30 com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource getPoolManager6 信息: Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, dataSourceName -> 1bqv9u3931kv3noythxveh|1786e64, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1bqv9u3931kv3noythxveh|1786e64, idleConnectionTestPeriod -> 0, initialPoolSize -> 10, jdbcUrl -> jdbc:mysql://localhost:3306/cms, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 0, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 10, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 2, numHelperThreads -> 3, numThreadsAwaitingCheckoutDefaultUser -> 0, preferredTestQuery -> null, properties -> {user=******, password=******}, propertyCycle -> 0, statementCacheNumDeferredCloseThreads -> 0, statementDestroyerNumActiveThreads -> -1, statementDestroyerNumConnectionsInUseAllUsers -> -1, statementDestroyerNumConnectionsInUseDefaultUser -> -1, statementDestroyerNumConnectionsWithDeferredDestroyStatementsAllUsers -> -1, statementDestroyerNumConnectionsWithDeferredDestroyStatementsDefaultUser -> -1, statementDestroyerNumDeferredDestroyStatementsAllUsers -> -1, statementDestroyerNumDeferredDestroyStatementsDefaultUser -> -1, statementDestroyerNumIdleThreads -> -1, statementDestroyerNumTasksPending -> -1, statementDestroyerNumThreads -> -1, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false ]7 <span style="color:#ff0000;">com.mchange.v2.c3p0.impl.NewProxyConnection@1e87719</span>

说明已经成功连接数据库,但是在创建ComboPooledDataSource类时会输出一堆日志,而且竟然是用System.err.println输出的,实在是令人不爽,想办法把它干掉。

 方法一:修改mchange-commons-java-0.2.3.3.jar中文件,没经过深入研究,不再赘述;

方法二:和Log4j配合使用(导入log4j.jar与log4j.properties);

log4j.properties

1 log4j.rootLogger=WARN,c12     log4j.appender.c1=org.apache.log4j.ConsoleAppender3     log4j.appender.c1.layout=org.apache.log4j.PatternLayout4     log4j.appender.c1.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%p] %m [%t] %c [%l]%n5     #log4j.appender.f1.File=/WEB-INF/logs/file.log6     #log4j.appender.f1=org.apache.log4j.DailyRollingFileAppender7     #log4j.appender.f1.layout=org.apache.log4j.PatternLayout8     #log4j.appender.f1.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss} [%p] %m [%t] %c [%l]%n

此时,控制台日志输出为

com.mchange.v2.c3p0.impl.NewProxyConnection@c62c8

至此,整个C3P0连接池配置完成,可直接在dao中访问数据库。