java jdbc线程池的使用

来源:互联网 发布:iphone制作视频软件 编辑:程序博客网 时间:2024/05/16 02:33

好久没直接使用jdbc了,今天重温了一下相关知识,并对连接池的使用写了简单的示例,记录在此以便需要的同行参考和方便自己查阅,不足之处欢迎批评指正。

1、dbcp数据源

所需jar包 dbcp:连接池的实现,commons-pool2:连接池实现的依赖

<dependency>    <groupId>org.apache.tomcat</groupId>    <artifactId>dbcp</artifactId>    <version>6.0.29</version></dependency><dependency>    <groupId>org.apache.commons</groupId>    <artifactId>commons-pool2</artifactId>    <version>2.0</version></dependency>
在这里我使用了单例模式来创建dbcp数据源,具体代码输入附上注释

private static Connection connection;private static String url="jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=utf-8";private static String user = "root";private static String password="root";private static String driverClassName="com.mysql.jdbc.Driver";private static Object obj=new Object();
//数据源对象private static BasicDataSource bds = null;
public static Connection getConnectionByPool(){    if (bds == null) {        synchronized (obj) {            if (bds == null) {                //创建数据源对象                bds = new BasicDataSource();                //设置连接池所需的驱动                bds.setDriverClassName(driverClassName);                bds.setUrl(url);                bds.setUsername(user);                bds.setPassword(password);                //设置连接池的初始连接数                bds.setInitialSize(10);                //设置连接池最多可以有多少个活动连接数                bds.setMaxActive(20);                //设置连接池最少有两个空闲的连接                bds.setMinIdle(2);                //通过数据源获取连接            }        }    }    try {        return bds.getConnection();    } catch (SQLException e) {        e.printStackTrace();        return  null;    }}

2、c3p0数据源

c3p0相比之下性能更胜一筹,Hibernate推荐使用c3p0连接池。可以自动清理不用的Connection、statement和resultset。

示例中同样采用单例模式来创建连接池,然后从连接池中获取Connection对象。

public static void initc3p0DataSource(){    synchronized (obj){        if (dataSource == null){            dataSource = new ComboPooledDataSource();            try {                //注册驱动                dataSource.setDriverClass(driverClassName);                //设置数据库url                dataSource.setJdbcUrl(url);                //设置数据库用户名                dataSource.setUser(user);                //设置数据库密码                dataSource.setPassword(password);                //设置连接池最大连接数                dataSource.setMaxPoolSize(40);                //设置最小连接数                dataSource.setMinPoolSize(2);                //设置初始连接数                dataSource.setInitialPoolSize(10);                //设置最大statement缓存数                dataSource.setMaxStatements(20);            } catch (PropertyVetoException e) {                e.printStackTrace();            }        }    }}public static Connection getConnectionFromc3p0(){    if (dataSource == null){        initc3p0DataSource();    }    if (dataSource != null){        try {            return dataSource.getConnection();        } catch (SQLException e) {            e.printStackTrace();            return null;        }    }    return null;}




0 0