C3P0的三种配置方式以及基本配置项详解

C3P0 数据库连接池配置
本文介绍 C3P0 数据库连接池的三种配置方式:通过 setters 设置、类路径下的 c3p0.properties 文件及 c3p0-config.xml 文件。详细解释了各配置项的意义,并给出示例代码。


    

     数据库连接池C3P0框架是个非常优异的开源jar,高性能的管理着数据源,这里只讨论程序本身负责数据源,不讨论容器管理。

     注:需要的jar包在后面给出链接。

     -------------------------------------------------------------------------------------------------------------------------------------------

     c3p0的配置方式分为三种,分别是
     1.setters一个个地设置各个配置项(不推荐)
     2.类路径下提供一个c3p0.properties文件

     3.类路径下提供一个c3p0-config.xml文件

     一、实现方式:

     1.自己动手写代码,实现数据源(setters一个个地设置各个配置项)

     例如:在类路径下配置一个属性文件,config.properties,内容如下:

     driverClass=xxx

     jdbcUrl=xxx

     user=xxx

     password=xxx

     ...

      

     然后代码中实现

      

     Properties props = new Properties();

     InputStream in = Thread.class.getResourceAsStream("config.properties");

     props.load(in);

     in.close();

      

     ComboPooledDataSource cpds = new ComboPooledDataSource();

     cpds.setDriverClass(props.getProperty("driverClass"));

     cpds.setJdbcUrl(props.getProperty("jdbcUrl"));

     cpds.setUser(props.getProperty("user"));

     cpds.setPassword(props.getProperty("password"));

     ...

     这里实现了一个数据源。

      

     也可以这样配置,在类路径下配置一个xml文件,config.xml

      

     <config>

     <source name="source1">

     <property name="user">root</property>

     <property name="password">xxx</property>

     <property name="url">xxx</property>

     <property name="driverClass">xxx</property>

     </source>

     <source name="source2">

     ...

     </source>

     </config>

      

     然后自己解析xml文件,这样可以实现多个数据源的配置。

     ---------------------------------------------------------------------------------------------------------------------------------------------------

     2.配置默认的熟悉文件

     类路径下提供一个c3p0.properties文件(不能改名)

     配置如下:

      

     c3p0.driverClass=com.MySQL.jdbc.Driver

     c3p0.jdbcUrl=jdbc:mysql://localhost:3306/jdbc

     c3p0.user=root

     c3p0.password=Java
     ...

     上面只提供了最基本的配置项,其他配置项参照文章后面的文档配置,记得是c3p0.后面加属性名就是了,最后初始化数据源的方式就是这样简单:
     ...
     DataSource  ds = new ComboPooledDataSource();
     return ds;
     获得数据库链接  return ds.getConnection()
     ...
     然后就可以使用数据源了,C3P0会对c3p0.properties进行自动解析的
     -------------------------------------------------------------------------------------------------------------------------------------------------------
     3.路径下提供一个c3p0-config.xml文件  

      

     这种方式使用方式与第二种差不多,但是有更多的优点
     (1).更直观明显,很类似hibernate和spring的配置
     (2).可以为多个数据源服务,提供default-config和named-config两种配置方式

     <c3p0-config>

       <default-config>   

         <property name="user">root</property>

         <property name="password">java</property>

         <property name="driverClass">com.mysql.jdbc.Driver</property>

         <property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbc</property>

         <property name="initialPoolSize">10</property>

         <property name="maxIdleTime">30</property>

         <property name="maxPoolSize">100</property>

         <property name="minPoolSize">10</property>

       </default-config>

      

       <named-config name="mySource">

         <property name="user">root</property>

         <property name="password">java</property>

         <property name="driverClass">com.mysql.jdbc.Driver</property>

         <property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbc</property>

         <property name="initialPoolSize">10</property>

         <property name="maxIdleTime">30</property>

         <property name="maxPoolSize">100</property>

         <property name="minPoolSize">10</property>

       </named-config>

     </c3p0-config>

      

     ...

     DataSource  ds = new ComboPooledDataSource("mySource");

     return ds;//获得数据源

     获得数据库链接 return ds.getConnection()

     ...

     这样就可以使用数据源了。
     下面给出第三种方式的例子代码:

     a. src下面的创建的c3p0-confit.xml文件

     [html] view plain copy
     在CODE上查看代码片派生到我的代码片

         <?xml version="1.0" encoding="UTF-8"?>  
         <c3p0-config>  
           <default-config>    
             <property name="user">sa</property>  
             <property name="password"></property>  
             <property name="driverClass">com.microsoft.jdbc.sqlserver.SQLServerDriver</property>  
             <property name="jdbcUrl">jdbc:microsoft:sqlserver://192.168.0.252:6252;databasename=szWq</property>  
             <property name="initialPoolSize">10</property>  
             <property name="maxIdleTime">30</property>  
             <property name="maxPoolSize">100</property>  
             <property name="minPoolSize">10</property>  
           </default-config>  
         </c3p0-config>  


     b.获取数据库连接的帮助类DBConn.java

     [java] view plain copy
     在CODE上查看代码片派生到我的代码片

         <span style="font-size:14px;">package com.weicky.db;  
           
         import java.sql.*;  
           
         import com.mchange.v2.c3p0.ComboPooledDataSource;  
           
         /**********************************************
          * 功能: 链接数据库代码  
          * 作者: 许助云  
          * 创建时间:2014-10-18上午10:28:27  
          * 修改时间:2014-10-18上午10:28:27  
          * 备注:
          *********************************************  
          */  
         public class DBConn {  
                   
                 private static ComboPooledDataSource ds = new ComboPooledDataSource();  
                 //取得链接  
                 public static Connection getConn() {  
                     try {  
                         return ds.getConnection();  
                     }catch (SQLException e) {  
                         throw new RuntimeException(e);  
                     }  
                 }         
                 // 关闭链接    
                 public static void close(Connection conn) throws SQLException {    
                     if (conn != null) {    
                         try {    
                             conn.close();    
                         } catch (SQLException e) {    
                             e.printStackTrace();    
                             throw e;    
                         }    
                     }    
                 }    
                 
                 public static void close(PreparedStatement pstate) throws SQLException {    
                     if(pstate!=null){    
                         pstate.close();    
                     }    
                 }    
                 public static void close(ResultSet rs) throws SQLException {    
                     if(rs!=null){    
                         rs.close();    
                     }    
                 }    
                   
         }  
         </span>  


     二、部分参数配置说明:

      

      

     1.最常用配置

     initialPoolSize:连接池初始化时创建的连接数,default : 3(建议使用)

     minPoolSize:连接池保持的最小连接数,default : 3(建议使用)

     maxPoolSize:连接池中拥有的最大连接数,如果获得新连接时会使连接总数超过这个值则不会再获取新连接,而是等待其他连接释放,所以这个值有可能会设计地很大,default : 15(建议使用)

     acquireIncrement:连接池在无空闲连接可用时一次性创建的新数据库连接数,default : 3(建议使用)

      

     2.管理连接池的大小和连接的生存时间

     maxConnectionAge:配置连接的生存时间,超过这个时间的连接将由连接池自动断开丢弃掉。当然正在使用的连接不会马上断开,而是等待它close再断开。配置为0的时候则不会对连接的生存时间进行限制。default : 0 单位 s(不建议使用)

     maxIdleTime:连接的最大空闲时间,如果超过这个时间,某个数据库连接还没有被使用,则会断开掉这个连接。如果为0,则永远不会断开连接,即回收此连接。default : 0 单位 s(建议使用)

     maxIdleTimeExcessConnections:这个配置主要是为了快速减轻连接池的负载,比如连接池中连接数因为某次数据访问高峰导致创建了很多数据连接,但是后面的时间段需要的数据库连接数很少,需要快速释放,必须小于maxIdleTime。其实这个没必要配置,maxIdleTime已经配置了。default : 0 单位 s(不建议使用)

      

     3.配置连接测试:

     automaticTestTable:配置一个表名,连接池根据这个表名用自己的测试sql语句在这个空表上测试数据库连接,这个表只能由c3p0来使用,用户不能操作。default : null(不建议使用)

     preferredTestQuery:与上面的automaticTestTable二者只能选一。自己实现一条SQL检测语句。default : null(建议使用)

     idleConnectionTestPeriod:用来配置测试空闲连接的间隔时间。测试方式还是上面的两种之一,可以用来解决MySQL8小时断开连接的问题。因为它保证连接池会每隔一定时间对空闲连接进行一次测试,从而保证有效的空闲连接能每隔一定时间访问一次数据库,将于MySQL8小时无会话的状态打破。为0则不测试。default : 0(建议使用)

     testConnectionOnCheckin:如果为true,则在close的时候测试连接的有效性。default : false(不建议使用)

     testConnectionOnCheckout:性能消耗大。如果为true,在每次getConnection的时候都会测试,为了提高性能,尽量不要用。default : false(不建议使用)

      

     4.配置PreparedStatement缓存:

     maxStatements:连接池为数据源缓存的PreparedStatement的总数。由于PreparedStatement属于单个Connection,所以这个数量应该根据应用中平均连接数乘以每个连接的平均PreparedStatement来计算。同时maxStatementsPerConnection的配置无效。default : 0(不建议使用)

     maxStatementsPerConnection:连接池为数据源单个Connection缓存的PreparedStatement数,这个配置比maxStatements更有意义,因为它缓存的服务对象是单个数据连接,如果设置的好,肯定是可以提高性能的。为0的时候不缓存。default : 0(看情况而论)

      

     5.重连相关配置

     acquireRetryAttempts:连接池在获得新连接失败时重试的次数,如果小于等于0则无限重试直至连接获得成功。default : 30(建议使用)

     acquireRetryDelay:连接池在获得新连接时的间隔时间。default : 1000 单位ms(建议使用)

     breakAfterAcquireFailure:如果为true,则当连接获取失败时自动关闭数据源,除非重新启动应用程序。所以一般不用。default : false(不建议使用)

     checkoutTimeout:配置当连接池所有连接用完时应用程序getConnection的等待时间。为0则无限等待直至有其他连接释放或者创建新的连接,不为0则当时间到的时候如果仍没有获得连接,则会抛出SQLException。其实就是acquireRetryAttempts*acquireRetryDelay。default : 0(与上面两个,有重复,选择其中两个都行)

      

     6.定制管理Connection的生命周期

     connectionCustomizerClassName:用来定制Connection的管理,比如在Connection acquire 的时候设定Connection的隔离级别,或者在Connection丢弃的时候进行资源关闭,

     就可以通过继承一个AbstractConnectionCustomizer来实现相关方法,配置的时候使用全类名。有点类似监听器的作用。default : null(不建议使用)

      

     7.配置未提交的事务处理

     autoCommitOnClose:连接池在回收数据库连接时是否自动提交事务。如果为false,则会回滚未提交的事务,如果为true,则会自动提交事务。default : false(不建议使用)

     forceIgnoreUnresolvedTransactions:这个配置强烈不建议为true。default : false(不建议使用)

     一般来说事务当然由自己关闭了,为什么要让连接池来处理这种不细心问题呢?

      

     8.配置debug和回收Connection

     unreturnedConnectionTimeout:为0的时候要求所有的Connection在应用程序中必须关闭。如果不为0,则强制在设定的时间到达后回收Connection,所以必须小心设置,保证在回收之前所有数据库操作都能够完成。这种限制减少Connection未关闭情况的不是很适用。建议手动关闭。default : 0 单位 s(不建议使用)

     debugUnreturnedConnectionStackTraces:如果为true并且unreturnedConnectionTimeout设为大于0的值,当所有被getConnection出去的连接unreturnedConnectionTimeout时间到的时候,就会打印出堆栈信息。只能在debug模式下适用,因为打印堆栈信息会减慢getConnection的速度default : false(不建议使用)

      

     其他配置项:因为有些配置项几乎没有自己配置的必要,使用默认值就好,所以没有再写出来。

      

      

     三、示例:

     示例采用第二种方式:

     1.c3p0.properties:

      
     Java代码  收藏代码

         #驱动  
         c3p0.driverClass=com.mysql.jdbc.Driver  
         #地址  
         c3p0.jdbcUrl=jdbc:mysql://localhost:3306/jdbc  
         #用户名  
         c3p0.user=root  
         #密码  
         c3p0.password=lovejava  
         #-------------------------------  
         #连接池初始化时创建的连接数  
         c3p0.initialPoolSize=3  
         #连接池保持的最小连接数  
         c3p0.minPoolSize=3  
         #连接池在无空闲连接可用时一次性创建的新数据库连接数,default:3  
         c3p0.acquireIncrement=3  
         #连接池中拥有的最大连接数,如果获得新连接时会使连接总数超过这个值则不会再获取新连接,而是等待其他连接释放,所以这个值有可能会设计地很大,default : 15  
         c3p0.maxPoolSize=15  
         #连接的最大空闲时间,如果超过这个时间,某个数据库连接还没有被使用,则会断开掉这个连接,单位秒  
         c3p0.maxIdleTime=100  
         #连接池在获得新连接失败时重试的次数,如果小于等于0则无限重试直至连接获得成功  
         c3p0.acquireRetryAttempts=30  
         #连接池在获得新连接时的间隔时间  
         c3p0.acquireRetryDelay=1000  

      

      2.ConnectionPool

      
     Java代码  收藏代码

         package com.study.pool;  
           
         import java.sql.Connection;  
         import java.sql.SQLException;  
           
         import javax.sql.DataSource;  
           
         import com.mchange.v2.c3p0.ComboPooledDataSource;  
           
         public class ConnectionPool {  
             private DataSource ds;  
             private static ConnectionPool pool;  
             private ConnectionPool(){  
                 ds = new ComboPooledDataSource();  
             }  
             public static final ConnectionPool getInstance(){  
                 if(pool==null){  
                     try{  
                         pool = new ConnectionPool();  
                     }catch (Exception e) {  
                         e.printStackTrace();  
                     }  
                 }  
                 return pool;  
             }  
             public synchronized final Connection getConnection() {    
                 try {  
                     return ds.getConnection();  
                 } catch (SQLException e) {       
                     e.printStackTrace();  
                 }  
                 return null;  
             }  
               
         }  

      

      3.PoolThread

      
     Java代码  收藏代码

         package com.study.pool;  
           
         import java.sql.Connection;  
         import java.sql.PreparedStatement;  
         import java.sql.ResultSet;  
         import java.sql.SQLException;  
           
         public class PoolThread extends Thread {  
             @Override  
             public void run(){  
                 ConnectionPool pool = ConnectionPool.getInstance();  
                 Connection con = null;  
                 PreparedStatement stmt= null;  
                 ResultSet rs = null;  
                 try{  
                     con = pool.getConnection();  
                     stmt = con.prepareStatement("select sysdate as nowtime from dual");  
                     rs = stmt.executeQuery();  
                     while(rs.next()){  
                         System.out.println(Thread.currentThread().getId()+"---------------开始"+rs.getString("nowtime"));  
                     }  
                 } catch (Exception e) {  
                     e.printStackTrace();  
                 }finally{  
                     try {  
                         rs.close();  
                         stmt.close();  
                         con.close();  
                     } catch (SQLException e) {  
                         e.printStackTrace();  
                     }  
                 }  
                 System.out.println(Thread.currentThread().getId()+"--------结束");  
             }  
         }  

      

      4.PoolMain

      
     Java代码  收藏代码

         package com.study.pool;  
           
         public class PoolMain {  
           
             /**
              * 数据源缓冲池 实例练习
              */  
             public static void main(String[] args) {  
                 System.out.println("缓冲池模拟开始");  
                 PoolThread[] threads = new PoolThread[50];  
                 for(int i=0;i<threads.length;i++){  
                     threads[i] = new PoolThread();  
                 }  
                 for(int i=0;i<threads.length;i++){  
                     threads[i].start();  
                 }  
             }  
           
         }  

     c3p0jar包下载http://pan.baidu.com/s/1gdtKpeN 引入mchange-commons-java-0.2.3.4.jar和c3p0-0.9.2.1.jar两个包
   

转载于:https://my.oschina.net/ruanjun/blog/885563

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值