ITeye博客

C3P0连接池详细配置

cms163 · 2009-10-10 16:47 · 数据库 · Markdown

我们许多人有的是使用的时应用服务器自带的数据连接池,有的是使用dbcp,c3p0,proxypool等数据库连接池,以前我直接使用hibernate的时候,这些连接池的配置按照hibernate的文档配置没有问题,这段时间配置的是c3p0的JDBC数据库连接池。 多话不说了,代码贴出来,希望对大家有所帮助。

定义一个接口,里面三个抽象方法: public interface IConnectionProvider { public void configure(Properties props); public Connection getConnection() throws SQLException; public void closeConnection(Connection conn) throws SQLException; public void close(); }

实现上面的三个接口,进行C3P0配置 public class C3P0ConnectionProvider implements IConnectionProvider { private DataSource ds;

private static final Log log = LogFactory.getLog(C3P0ConnectionProvider.class);

public void configure(Properties props) {
    String jdbcDriverClass = props.getProperty(Constant.JDBC_DRIVER);//JDBC驱动
    try {
        Class.forName(jdbcDriverClass);
        String username = props.getProperty(Constant.JDBC_USERNAME);//jdbc连接用户名
        String password = props.getProperty(Constant.JDBC_PASSWORD);//jdbc连接密码
        String url = props.getProperty(Constant.JDBC_URL);//jdbc连接url字符串
        DataSource ds_unpooled = DataSources.unpooledDataSource(url, username, password);
        
        Properties overrides = new Properties();
        String minSize = props.getProperty(Constant.JDBC_MINPOOLSIZE);
        if (minSize == null || minSize.length() == 0) {
            minSize = "10";
        }
        String maxSize = props.getProperty(Constant.JDBC_MAXPOOLSIZE);
        if (maxSize == null || maxSize.length() == 0) {
            maxSize = "30";
        }

        overrides.put("minPoolSize", Integer.parseInt(minSize));
        overrides.put("maxStatements", "200"); 
        overrides.put("maxPoolSize", Integer.parseInt(maxSize));

        ds = DataSources.pooledDataSource(ds_unpooled, overrides);
    } catch (Exception e) {
        log.error("jdbc driver class not found ,the driver class is " + jdbcDriverClass, e);
    }
}

public Connection getConnection() throws SQLException {
    final Connection conn = ds.getConnection();
    return conn;
}

public void closeConnection(Connection conn) throws SQLException {
    conn.close();
}

public void close() {
    try {
        DataSources.destroy(ds);
    } catch (SQLException sqle) {
        log.warn("could not destroy C3P0 connection pool", sqle);
    }
}

}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。