jdbc-----连接池c3po

<dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
</dependency>
public class ConnectionManager {

    private static ComboPooledDataSource ds = null;

    private static ConnectionManager connManger; 


    public final static ConnectionManager getInstance() {        
        return connManger;
    }
public final ComboPooledDataSource getDataSource() {
        return ds;
    }

 

public final Connection getConnection() {
        try {
            if (ds==null) {
                new ConnectionManager();
            }
            return ds.getConnection();
        } catch (SQLException e) {
            logger.error("无法从数据源获取连接 ");
            return null;
        }
    }

    public ConnectionManager() {
        try {
            ds = new ComboPooledDataSource();
            ds.setDriverClass("");
            ds.setJdbcUrl("");
            ds.setUser("");
            ds.setPassword("");
            ds.setAcquireIncrement(6);            // 当连接池中的连接用完时,C3P0一次性创建新连接的数目
            ds.setAcquireRetryAttempts(30);     // 从数据库获取新连接失败后重复尝试获取的次数    
            ds.setAcquireRetryDelay(1000);        // 两次连接中间隔时间,单位毫秒,默认为1000    
            ds.setAutoCommitOnClose(false);        // 连接关闭时默认将所有未提交的操作回滚。默认为false
            ds.setIdleConnectionTestPeriod(60); // 隔多少秒检查所有连接池中的空闲连接,默认为0表示不检查
            ds.setMinPoolSize(9);                  // 连接池中保留的最小连接数。默认为3
            ds.setMaxPoolSize(90);                 // 连接池中保留的最大连接数。默认为15
            ds.setMaxIdleTime(60);              // 超过空闲时间的连接将被丢弃。为0或负数则永不丢弃。默认为0
            ds.setInitialPoolSize(9);             // 初始化连接数
            if (Global.DRIVER.equals("com.mysql.jdbc.Driver")) {
                ds.setPreferredTestQuery("select 1 from t_task_quartz limit 1");
            } if (Global.DRIVER.equals("oracle.jdbc.driver.OracleDriver")) {
                ds.setPreferredTestQuery("select 1 from t_task_quartz where rownum=1");
            }        
        } catch (PropertyVetoException e) {
            logger.error(e.getMessage());
        }  
    }
}
    ComboPooledDataSource ds = ConnectionManager.getInstance().getDataSource();
    logger.info("----- 
                " , 数据库连接: " + ds.getNumConnections() + " , 使用: " + ds.getNumBusyConnections() + " , 空闲: " + ds.getNumIdleConnections());

 

posted @ 2020-05-20 14:47  sunjinwei123  阅读(226)  评论(0)    收藏  举报