MYSQL 之 JDBC(十五):数据库连接池

在使用开发基于数据库的web程序时,传统的模式基本是按一下步骤:

  • 在主程序(如servlet、bean)中建立数据库连接
  • 进行sql操作
  • 断开数据库连接

这种模式开发存在各种各样的问题,最重要的是:数据库的连接资源并没有得到很好的重复利用。

为解决传统开发中的数据库连接问题,可以采用数据库连接池技术,其基本思想就是为数据库连接建立一个“缓冲池”。预先在缓冲池中放入一定数量的连接,当需要建立数据库连接时,只需要从“缓冲池”中取出一个,使用完毕之后再放回去。

数据库连接池:负责分配、管理和释放数据库连接,它允许应用程序重复使用一个现有的数据库连接,而不是重新建立一个。

数据库连接池在初始化时,将创建一定数量的数据库连接放到连接池中,这些数据库连接的数量是由最小数据库连接数来设定的。无论这些数据库连接是否被使用,连接池都将一直保持至少拥有这么多的连接数量。连接池的最大数据库连接数量限定了这个连接池能占有的最大连接数,当应用程序向连接池请求的连接数超过最大连接数量时,这些请求将被加入到等待队列中。

数据库连接池技术的优点

  • 资源重用
  • 更快的系统反应速度
  • 新的资源分配手段
  • 统一的连接管理,避免数据库连接泄露

两种开源的数据库连接池

  JDBC的数据库连接池使用javax.sql.DataSource来表示,DataSource只是一个接口,该接口通常由服务器(Weblogic,WebSphere,Tomcat)提供实现,也有一些开源组织提供实现

  • DBCP
  • C3P0

  DataSource通常被称为数据源,它包含连接池和连接池管理两个部分,习惯上也经常把DataSource称为连接池

DBCP测试,Tomcat内置

  1. 加入jar包(2个包)dbcp和pool
  2. 创建数据库连接池

DBCP工厂测试

扫描二维码关注公众号,回复: 11379298 查看本文章

  加载dbcp的properties配置文件:配置文件中的键值对,键需要来自BasicDataSource的属性
  调用BasicDataSourceFactory的createDataSource方法创建DataSource实例
  从DataSource实例中获取数据库连接

dbcp.properties

username=root
password=123456
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/testjdbc?serverTimezone=GMT%2B8

initialSize=10
maxTotal=50
minIdle=5
maxWaitMillis=5000

DBCP测试

package com.litian.jdbc;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author: Li Tian
 * @contact: [email protected]
 * @software: IntelliJ IDEA
 * @file: TestDBCP.java
 * @time: 2020/4/6 13:28
 * @desc: |使用DBCP数据库连接池
 */

public class TestDBCP {
    
    public static void main(String[] args) throws Exception {
        testDBCPwithDataSourceFactory();
    }

    /**
     * 利用DBCP工厂建立连接池
     */
    public static void testDBCPwithDataSourceFactory() throws Exception {
        Properties p = new Properties();
        InputStream is = TestDBCP.class.getClassLoader().getResourceAsStream("dbcp.properties");
        p.load(is);
        DataSource ds = BasicDataSourceFactory.createDataSource(p);
        System.out.println(ds.getConnection());

        BasicDataSource bs = (BasicDataSource) ds;
        System.out.println(bs.getMaxWaitMillis());
    }

    public static void testDBCP(){
        // 1. 创建DBCP数据源实例
        BasicDataSource ds = null;
        ds = new BasicDataSource();
        // 2. 为数据源实例指定必须的属性
        ds.setUsername("root");
        ds.setPassword("123456");
        ds.setUrl("jdbc:mysql://localhost:3306/testjdbc?serverTimezone=GMT%2B8");
        ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
        // 3. 指定数据源的一些可选属性
        // 3.1 指定数据库连接池初始化连接数的个数
        ds.setInitialSize(10);
        // 3.2 指定最大的连接数,现在的代码中已经没有setMaxActive这个方法名了
        // 同一时刻可以同时向数据库申请的连接数
        ds.setMaxTotal(50);
        // 3.3 指定小连接数
        // 在数据库中连接池中最少有多少个空闲连接数
        ds.setMinIdle(5);
        // 3.4 等待连接池分配连接,最长的等待时间.单位为毫秒,超出该时间抛异常。
        ds.setMaxWaitMillis(1000 * 5);

        try {
            // 4. 从数据源中获取数据库连接
            Connection conn = ds.getConnection();
            System.out.println(conn);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
View Code

C3P0

  加入jar包(2个包)C3P0和mchange-commons-java
  创建数据库连接池
C3P0工厂测试,Hibernate官方推荐,参考连接

  在src创建一个c3p0-config.xml文件
  创建ComboPooledDataSource实例
  从DataSource实例中获取数据库连接

c3p0-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
    <!-- 这是默认配置信息 -->
    <default-config>
        <!-- 连接四大参数配置 -->
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbctest</property>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="user">root</property>
        <property name="password">root</property>
        <!-- 池参数配置 -->
        <property name="acquireIncrement">3</property>
        <property name="initialPoolSize">10</property>
        <property name="minPoolSize">2</property>
        <property name="maxPoolSize">10</property>
    </default-config>

    <!-- 专门为oracle提供的配置信息 -->
    <named-config name="oracle-config">
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/mydb1</property>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="user">root</property>
        <property name="password">123</property>
        <property name="acquireIncrement">3</property>
        <property name="initialPoolSize">10</property>
        <property name="minPoolSize">2</property>
        <property name="maxPoolSize">10</property>
    </named-config>

    <!-- 专门为Mysql提供的配置信息 -->
    <named-config name="mysql-config">
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/testjdbc?serverTimezone=GMT%2B8</property>
        <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
        <property name="user">root</property>
        <property name="password">123456</property>

        <!-- 若数据库中连接数不足时,一次向数据库服务器申请多少个连接 -->
        <property name="acquireIncrement">5</property>
        <!-- 初始化数据库连接池时连接的数量 -->
        <property name="initialPoolSize">5</property>
        <!-- 数据库连接池中最小的数据库连接数 -->
        <property name="minPoolSize">5</property>
        <!-- 数据库连接池中最大的数据库连接数 -->
        <property name="maxPoolSize">10</property>

        <!-- C3P0数据库连接池可以维护的Statement的个数 -->
        <property name="maxStatements">20</property>
        <!-- 每个连接同时可以使用的Statement对象的个数 -->
        <property name="maxStatementsPerConnection">5</property>

    </named-config>
</c3p0-config>
View Code

C3P0测试

package com.litian.jdbc;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.sql.Connection;

/**
 * @author: Li Tian
 * @contact: [email protected]
 * @software: IntelliJ IDEA
 * @file: TestC3P0.java
 * @time: 2020/4/6 14:40
 * @desc: |使用C3P0数据库连接池
 */

public class TestC3P0 {

    public static void main(String[] args) throws Exception {
        // test2();
        test3();
    }

    public static void test3() throws Exception{
        Connection conn = JDBCTools.getDSConnection();
        System.out.println(conn);
    }

    public static void test2() throws Exception{
        DataSource ds = new ComboPooledDataSource("mysql-config");
        System.out.println(ds.getConnection());
        ComboPooledDataSource cpds = (ComboPooledDataSource) ds;
        System.out.println(((ComboPooledDataSource) ds).getMaxStatements());
    }

    public static void test1() throws Exception{
        ComboPooledDataSource cpds = new ComboPooledDataSource();
        cpds.setDriverClass("com.mysql.cj.jdbc.Driver");
        cpds.setJdbcUrl("jdbc:mysql://localhost:3306/testjdbc?serverTimezone=GMT%2B8");
        cpds.setUser("root");
        cpds.setPassword("123456");
        System.out.println(cpds.getConnection());
    }
}
View Code

修改JDBCTools工具类,加入数据库连接池功能

private static DataSource ds = null;

// 数据库连接池应只被初始化一次。
static {
    ds = new ComboPooledDataSource("mysql-config");
}

public static Connection getDSConnection() throws Exception {
    return ds.getConnection();
}

————————————————
版权声明:本文为CSDN博主「李英俊小朋友」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_21579045/article/details/105386353

猜你喜欢

转载自www.cnblogs.com/qiu-hua/p/13199756.html