Java 数据库连接池C3P0,德鲁伊(Druid)的详解

博主前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住也分享一下给大家,
👉点击跳转到网站

一、Java中数据库连接池的基本介绍
在这里插入图片描述

数据库连接池的示意图
在这里插入图片描述

二、数据库连接池的种类
在这里插入图片描述

三、C3P0数据库连接池的使用,代码如下

public class C3P0_ {
    //1.方式1:相关参数,在程序中指定user,url,password等
    @Test
    public void testC3P0_01() throws Exception {
        //1.创建一个数据源对象
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();

        //2.通过配置mysql.properties获取相关连接信息
        //通过Properties,获取相关配置文件的信息
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\mysql.properties"));
        //获取相关的值
        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次操作
        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));//C3P0 5000次连接mysql耗时:1038
    }

    //第二种方式,使用配置文件模板来完成
    //1.将c3p0提供的 拷贝到src目录下
    //2.该文件指定了连接数据库和连接池的相关参数
    @Test
    public void testC3P0_02() throws Exception {
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource("ly_edu");
        //测试5000次连接mysql
        long start=System.currentTimeMillis();
        System.out.println("开始执行");
        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));//C3P0 5000次连接mysql耗时:1026
    }
}

第二种方式需要使用配置模板来完成,将c3p0-config.xml拷贝到src目录下,就可以使用了,c3p0-config.xml代码如下

<c3p0-config>
    <!--数据库源名称代表连接池-->
    <named-config name="ly_edu">
        <!-- 使用默认的配置读取连接池对象-->
        <!--  连接参数 -->
        <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/db_ly?serverTimezone=GMT</property>
        <property name="user">root</property>
        <property name="password">123456</property>

        <!-- 连接池参数 -->
        <!--每次增长的连接数-->
        <property name="acquireIncrement">5</property>
        <!-- 初始连接数 -->
        <property name="initialPoolSize">10</property>
        <!--最小连接数-->
        <property name="minPoolSize">5</property>
        <!-- 最大连接数 -->
        <property name="maxPoolSize">10</property>

        <!--可连接的最多的命令对象数-->
        <property name="maxStatements">5</property>

        <!--每个连接对象可连接的最多的命令对象数-->
        <property name="maxStatementsPerConnection">2</property>
    </named-config>
</c3p0-config>

四、德鲁伊(Druid)数据库连接池的使用,代码如下

public class Druid_ {
    @Test
    public void testDruid() throws Exception {
        //1.加入Druid jar包
        //2.加入配置文件,将该文件拷贝到项目的src目录下
        //3.创建Properties对象,读取配置文件
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\druid.properties"));

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

五、将 Java 中封装JDBC连接到JDBCUtils工具类的详解 这边文章中的JDBCUtils工具类,更新为通过Druid数据库连接池得到连接和关闭资源。

JDBCUtilsByDruid工具类代码如下

//基于druid数据库连接池的工具类
public class JDBCUtilsByDruid {

    private static DataSource ds;

    //在静态代码块完成 ds初始化
    static {
        try {
            Properties properties = new Properties();
            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);
        }
    }
}

JDBCUtilsByDruid工具类的使用

public class JDBCUtilsByDruid_Use {
    @Test
    public void testSelect() {
        Connection connection = null;
        String sql = "SELECT id,name,borndate FROM ACTOR WHERE id = ?";
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            //1.得到连接
            connection = JDBCUtilsByDruid.getConnection();
            System.out.println(connection.getClass());//class com.alibaba.druid.pool.DruidPooledConnection
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1, 2);
            //执行得到结果集
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                String name = resultSet.getString("name");
                int id = resultSet.getInt("id");
                Date borndate = resultSet.getDate("borndate");
                System.out.println(id + "\t" + name + "\t" + borndate);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtilsByDruid.close(resultSet, preparedStatement, connection);
        }
    }
}

输出结果如下

class com.alibaba.druid.pool.DruidPooledConnection
2	王宝强	1980-01-03
  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 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
发出的红包

打赏作者

路宇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值