C3P0和Druid数据库连接池的使用

本次博客带领大家学习C3P0和Druid数据库连接池的使用。

传统方式连接数据库

  • 连接5000次数据库的耗时。
public void testCon(){

    //看看连接 - 关闭 connection 会耗用多久
    System.out.println("开始执行");
    long start = System.currentTimeMillis();
    for (int i=0;i<5000;i++){
        //使用传统的jdbc方式,得到连接
        Connection connection = JDBCUtils.getConnection();

        //关闭
        JDBCUtils.close(null,null,connection);
    }
    long end = System.currentTimeMillis();
    System.out.println("传统方式连接 5000次数据库 耗时="+(end-start));
}

C3P0数据库连接池的使用

  • 方式一:传入相关参数,在程序中指定user,url,password等。
public void testC3P0_01() throws Exception {
    //1.创建一个数据源对象
    ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
    //2.通过配置文件mysql.properties 获取相关连接的信息。
    Properties properties = new Properties();
    properties.load(new FileInputStream("src\\mysql.properites"));
    String user = properties.getProperty("user");
    String password = properties.getProperty("password");
    String driver = properties.getProperty("driver");
    String url = properties.getProperty("url");

    //给数据源  comboPooledDataSource 设置相关的参数
    //注意:连接管理是由 comboPooledDataSource 来管理
    comboPooledDataSource.setDriverClass(driver);
    comboPooledDataSource.setJdbcUrl(url);
    comboPooledDataSource.setUser(user);
    comboPooledDataSource.setPassword(password);
    //设置初始化连接数
    comboPooledDataSource.setInitialPoolSize(10);
    comboPooledDataSource.setMaxPoolSize(50);
    //测试连接池的效率,测试对mysql 5000次操作
    System.out.println("开始执行");
    long start = System.currentTimeMillis();
    for (int i=0;i<5000;i++){
        Connection connection = comboPooledDataSource.getConnection();//这个方法就是从 DataSource 来实现
        connection.close();
    }
    long end = System.currentTimeMillis();
    System.out.println("c3p0 5000次连接mysql 耗时="+(end-start));
}
  • 方式二:使用配置文件模板来完成。
<?xml version="1.0" encoding="utf-8"?>
<--!>xml配置文件</--!>
<c3p0-config>
  <default-config>
    <property name="driverClass">com.mysql.jdbc.Driver</property>
    <property name="jdbcUrl">jdbc:mysql://localhost:3306/ld_db01</property>
    <property name="user">root</property>
    <property name="password">root</property>
    
    <property name="initialPoolSize">5</property>
    <property name="maxPoolSize">10</property>
    <property name="checkoutTimeout">3000</property>
  </default-config>

  <named-config name="otherc3p0"> 
  </named-config>
</c3p0-config>
//1.将c3p0 提供c3p0-config.xml 拷贝到 src目录下
//2. 该文件指定了连接数据库和连接池的相关参数
@Test
public void testC3P0_02() throws Exception {
    ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
    System.out.println("开始执行");
    long start = System.currentTimeMillis();
    for (int i=0;i<5000;i++){
        Connection connection = comboPooledDataSource.getConnection();
        connection.close();
    }
    long end = System.currentTimeMillis();
    System.out.println("c3p0 第二次方式 5000次连接mysql 耗时="+(end-start));

}

Druid数据库连接池的使用

  1. 加入 Druid jar包。

  2. 加入配置文件 druid.properties,将该文件拷贝项目的src目录。

  3. 创建Properties对象,读取配置文件。

  4. 创建一个指定参数的数据库连接池。

driverClassName = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/ld_db01?rewriteBatchedStatements=true
username = root
password = root
initialSize=10
minIdle=5
maxActive=20
maxWait=5000
public void testDruid() throws Exception {
    //1.加入 Druid jar包
    //2. 加入配置文件 druid.properties,将该文件拷贝项目的src目录。
    //3. 创建Properties对象,读取配置文件。
    Properties properties = new Properties();
    properties.load(new FileInputStream("src\\druid.properties"));

    //4.创建一个指定参数的数据库连接池,Druid连接池
    DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
    System.out.println("开始执行");
    long start = System.currentTimeMillis();
    for (int i=0;i<500000;i++){
        Connection connection = dataSource.getConnection();
        connection.close();
    }
    long end = System.currentTimeMillis();
    System.out.println("druid连接池 500000次连接mysql 耗时="+(end-start));
}

Druid工具类

  • 将JDBCUtils工具类改成Druid(德鲁伊)实现。
public class JDBCUtilsByDruid {
    private  static DataSource ds;

    //在静态代码块完成 ds初始化
    static {
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream("src\\druid.properties"));
            ds = DruidDataSourceFactory.createDataSource(properties);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //编写getConnection 方法
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }

    //关闭连接,在数据库连接池技术中,close不是真的断掉连接,而是把使用的Connection对象放回连接池
    public static void close(ResultSet resultSet, Statement statement,Connection connection){
        try {
            if (resultSet != null){
                resultSet.close();
            }
            if (statement !=null){
                statement.close();
            }
            if (connection !=null){
                connection.close();
            }
        } catch (SQLException e) {
            throw  new RuntimeException(e);
        }
    }
}
public class JDBCUtilsByDruid_USE {
    @Test
    public void testSelect(){
        System.out.println("使用Druid数据库连接池查询:");
        //1. 得到连接
        Connection connection = null;

        // 2.组织一个sql
        String sql = "select * from actor";
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        //3.创建PrepareStatement对象
        try {
            connection = JDBCUtilsByDruid.getConnection();
            preparedStatement = connection.prepareStatement(sql);
            resultSet = preparedStatement.executeQuery();
            while(resultSet.next()){
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                String sex = resultSet.getString("sex");
                Date borndate = resultSet.getDate("borndate");
                String phone = resultSet.getString("phone");
                System.out.println(id+"\t"+name+"\t"+sex+"\t"+borndate+"\t"+phone);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //关闭资源
            JDBCUtilsByDruid.close(null,preparedStatement,connection);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我会回答你的问题,以下是常用数据库连接池 DBCP、c3p0Druid配置说明: 1. DBCP (Apache Commons DBCP) DBCP 是 Apache Commons 项目中的一个子项目,它是一个纯 Java 实现的数据库连接池。DBCP 的使用非常简单,只需要引入相关的 jar 包即可。以下是 DBCP 的配置说明: ``` # 最大连接数 maxActive=100 # 最大空闲连接数 maxIdle=30 # 最小空闲连接数 minIdle=10 # 获取连接时的最大等待时间,单位为毫秒 maxWait=10000 # 是否开启自动回收空闲连接的线程 removeAbandoned=true # 回收超时时间,单位为秒 removeAbandonedTimeout=180 # 是否开启缓存 PreparedStatement,提高性能 poolPreparedStatements=true # 缓存 PreparedStatement 的最大数量 maxOpenPreparedStatements=100 ``` 2. c3p0 c3p0 是一个开源的 JDBC 数据库连接池,它实现了数据源和 JNDI 绑定,支持 JDBC3 的 Connection 和 Statement 缓存以及 JDBC4 的自动化管理。以下是 c3p0配置说明: ``` # 最大连接数 c3p0.maxPoolSize=100 # 最小连接数 c3p0.minPoolSize=10 # 初始化连接数 c3p0.initialPoolSize=10 # 获取连接时的最大等待时间,单位为毫秒 c3p0.checkoutTimeout=10000 # 是否自动回收超时连接 c3p0.autoCommitOnClose=true # 是否开启自动回收空闲连接的线程 c3p0.idleConnectionTestPeriod=60 # 回收超时时间,单位为秒 c3p0.maxIdleTime=1800 # 是否开启缓存 PreparedStatement,提高性能 c3p0.cachePreparedStatements=true # 缓存 PreparedStatement 的最大数量 c3p0.maxStatements=100 ``` 3. Druid Druid 是阿里巴巴开源的一个高性能、可扩展、功能强大的数据库连接池。它主要提供了以下功能:监控统计、防御 SQL 注入、批量处理、数据源加密、日志记录等。以下是 Druid配置说明: ``` # 最大连接数 druid.maxActive=100 # 最大空闲连接数 druid.maxIdle=30 # 最小空闲连接数 druid.minIdle=10 # 获取连接时的最大等待时间,单位为毫秒 druid.maxWait=10000 # 是否开启自动回收空闲连接的线程 druid.removeAbandoned=true # 回收超时时间,单位为秒 druid.removeAbandonedTimeout=180 # 是否开启缓存 PreparedStatement,提高性能 druid.poolPreparedStatements=true # 缓存 PreparedStatement 的最大数量 druid.maxOpenPreparedStatements=100 # 是否开启 SQL 执行监控 druid.stat=true # 是否开启防御 SQL 注入功能 druid.filters=stat,wall,log4j ``` 以上就是常用数据库连接池 DBCP、c3p0Druid配置说明。希望对你有所帮助!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值