c3p0连接池

c3p0连接池(ThreadLocal保证connection线程安全)

C3P0是一个开放源代码的JDBC连接池,它在lib目录中与Hibernate一起发布,包括了实现jdbc3和jdbc2扩展规范说明的Connection 和Statement 池的DataSources 对象。

下载c3p0的jar,并添加log4j.jar

先便给大减提供一个参c3p0数据库连接池的小例子借此介绍一下参数配置:

package com.wb.db;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
* 采用ThreadLocal线程局部变量保证线程安全
* @author hemes1314
*/
public class C3p0Pool {

public static ThreadLocal connectionHolder = new ThreadLocal();

private static DataSource dataSource;

    public C3p0Pool(){  
    }  

    public static Connection getConnection() {
   
    Connection conn = (Connection) connectionHolder.get();
    //如果在当前线程中没有绑定相应的Connection
    if(conn==null){
         if (dataSource == null) {  
             initDataSource();
         }  
         try {  
             conn = dataSource.getConnection();
             //将Connection设置到ThreadLocal线程变量中
             connectionHolder.set(conn);
         } catch (SQLException e) {  
             // TODO Auto-generated catch block  
             e.printStackTrace();  
         }
    }
        return conn;  
    }
   
    public static void closeConnection(){
    Connection conn = (Connection) connectionHolder.get();
    if(conn!=null){
       try {
     conn.close();
     //从ThreadLocal中清除Connection
     connectionHolder.remove();
    } catch (SQLException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
    }
    }
   
    public static void initDataSource(){  
     String driverClassName=null;  
        String url=null;  
        String username=null;  
        String password=null;  
        int initialPoolSize=3;  
        int maxPoolSize=15;
        int minPoolSize=5;
        int acquireRetryDelay=1000;
        int maxIdleTime=60;


    Configuration config=new Configuration("oraConn.properties");
        driverClassName = config.getValue("driver");  
        url = config.getValue("url");
        username = config.getValue("user");
        password = config.getValue("password");  

        initialPoolSize = Integer.parseInt(config.getValue("initialPoolSize").trim());      
        maxPoolSize = Integer.parseInt(config.getValue("maxPoolSize").trim());
        minPoolSize = Integer.parseInt(config.getValue("minPoolSize").trim());
        maxIdleTime = Integer.parseInt(config.getValue("maxIdleTime").trim());

        ComboPooledDataSource cpds = new ComboPooledDataSource();   
        try {
    cpds.setDriverClass(driverClassName);
   } catch (PropertyVetoException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
        cpds.setUser(username);  
    cpds.setPassword(password);  
    cpds.setJdbcUrl(url);

    //初始化时获取三个连接,取值应在minPoolSize与maxPoolSize之间。Default: 3 initialPoolSize  
    cpds.setInitialPoolSize(initialPoolSize);  
    //连接池中保留的最大连接数。Default: 15 maxPoolSize  
    cpds.setMaxPoolSize(maxPoolSize);
    //连接池中保留的最小连接数。  
    cpds.setMinPoolSize(minPoolSize);
    //获得连接的最大等待毫秒数。Default: 1000 acquireRetryDelay
    cpds.setAcquireRetryDelay(acquireRetryDelay);
    //最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 maxIdleTime  
    cpds.setMaxIdleTime(maxIdleTime);
   
   
    //当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 acquireIncrement  
    //cpds.setAcquireIncrement(3);  
   
    //每60秒检查所有连接池中的空闲连接。Default: 0 idleConnectionTestPeriod  
    //cpds.setIdleConnectionTestPeriod(60);
   
    //连接关闭时默认将所有未提交的操作回滚。Default: false autoCommitOnClose  
    //cpds.setAutoCommitOnClose(true);
   
    //JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0
    //cpds.setMaxStatements(1);

    //maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数
    //cpds.setMaxStatementsPerConnection(100);

    //定义所有连接测试都执行的测试语句。在使用连接测试的情况下这个一显著提高测试速度。注意:测试的表必须在初始数据源的时候就存在。Default: null preferredTestQuery  
    //cpds.setPreferredTestQuery("select sysdate from dual");  
   
    // 因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection提交的  
    // 时候都将校验其有效性。建议使用idleConnectionTestPeriod或automaticTestTable  
    // 等方法来提升连接测试的性能。Default: false testConnectionOnCheckout  
    //cpds.setTestConnectionOnCheckout(true);
   
    //如果设为true那么在取得连接的同时将校验连接的有效性。Default: false testConnectionOnCheckin  
    //cpds.setTestConnectionOnCheckin(true);  
      
    //定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 acquireRetryAttempts  
    //cpds.setAcquireRetryAttempts(30);    
   
    //获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效  
    //保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试  
    //获取连接失败后该数据源将申明已断开并永久关闭。Default: false breakAfterAcquireFailure  
    //cpds.setBreakAfterAcquireFailure(false);  
    dataSource = cpds;       
    }
   
    /* 用于测试连接状态的方法*/
    public static void main(String[] args) {
    ComboPooledDataSource ds=(ComboPooledDataSource)dataSource;  
     try {
    System.out.println(ds.getConnection());
   } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
     //System.out.println(ds.getInitialSize());  
     //System.out.println(ds.getNumActive());  
     //System.out.println(ds.getNumIdle());  
     //System.out.println(ds.getDefaultAutoCommit());
}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值