JDBC中常见的几种连接池jar包使用?

JDBC中常见的几种连接池jar包使用?

本文介绍JDBC中常见的几种连接池jar包使用 C3P0、Druid、HikariCP 、DBCP

初学者在学习连接池的时候很少用maven项目添加依赖,下面介绍的都是原始

的jar包使用,配置文件放src路径下。

什么是连接池?

连接池是一种用于管理数据库连接的技术,它具有以下好处:

  1. 提高性能:连接池可以重复使用已经建立的数据库连接,避免了每次请求都需要重新建立连接的开销。这样可以减少连接的创建和销毁次数,提高了数据库操作的效率。
  2. 节省资源:连接池可以控制同时存在的数据库连接数量,避免了过多的连接占用系统资源,提高了系统的稳定性和可靠性。
  3. 提升并发能力:连接池可以管理多个数据库连接,使得多个请求可以同时进行数据库操作,提高了系统的并发能力。
  4. 降低系统压力:连接池可以对数据库连接进行管理和监控,可以检测到连接的空闲时间和超时时间,及时释放无用的连接,避免了因为连接过多而导致系统崩溃或性能下降的问题。
  5. 提供连接的复用:连接池可以将连接分配给不同的请求,实现连接的复用,减少了连接的创建和销毁的次数,提高了系统的性能和效率。

总的来说,使用连接池可以提高系统的性能、稳定性和并发能力,节省系统资源,降低系统压力,提高数据库操作的效率。

C3P0

jar包下载地址

c3p0:JDBC DataSources/Resource Pools download | SourceForge.net

解压之后把下面两个jar包添加到库,新版需要添加这两个到库中

在这里插入图片描述

添加xml配置文件,文件名c3p0-config.xml固定的

<c3p0-config>
    <!--使用默认的配置读取数据库连接池对象 -->
    <default-config>
        <!--  连接参数 -->
        <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/java001?useServerPrepStmts=true</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">
        <!--  连接参数 -->
        <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/java001?useServerPrepStmts=true</property>
        <property name="user">root</property>
        <property name="password">root</property>

        <!-- 连接池参数 -->
        <property name="initialPoolSize">5</property>
        <property name="maxPoolSize">8</property>
        <property name="checkoutTimeout">1000</property>
    </named-config>
</c3p0-config>

测试代码:

@Test
public void testC3p0() throws SQLException {
    // 使用named-config命名的配置,默认不用传入
    ComboPooledDataSource comboPooledDataSource =
            new ComboPooledDataSource("otherC3p0");
    Connection connection = comboPooledDataSource.getConnection();
    System.out.println(connection);
}

输出结果:

在这里插入图片描述

c3p0需要配置log4j日志不然的话控制台会输出很多日志信息

【log4j】下载、安装、使用_log4j下载-CSDN博客

配置文件log4j.properties

#日志打印的级别及目的地	debug>info>warn>error>fatal
#stdout控制台	logfile日志文件
log4j.rootLogger=debug,logfile

# Console output...打印到控制台
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss}  %F %p %m%n

#日志文件打印设置
log4j.appender.logfile=org.apache.log4j.FileAppender
#日志的文件地址
log4j.appender.logfile.File=gdLog.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %l %F %p %m%n

Druid

德鲁伊jar下载博主使用的是1.2.0版本

Central Repository: com/alibaba/druid (maven.org)

添加配置文件文件名不固定

driverClassName = com.mysql.cj.jdbc.Driver
url = jdbc:mysql://localhost:3306/bankdb?useServerPrepStmts=true 
username = root   
password = root
initialSize = 10
maxActive = 30
maxWait = 1000

测试代码:

@Test
public void testDruid() throws Exception {
    // 创建配置文件对象
    Properties properties = new Properties();
    // 创建一个文件输入流指向配置文件
    FileInputStream inputStream = new FileInputStream("src\\jdbc.properties");
    // 加载配置文件
    properties.load(inputStream);
    // 工厂包装类创建数据源
    DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
    System.out.println(dataSource.getConnection());
}

输出结果:

在这里插入图片描述

HikariCP

HikariCP 也需要配置log4j日志

光连接池jar包下载

Maven Repository: com.zaxxer » HikariCP » 4.0.3 (mvnrepository.com)

在这里插入图片描述

使用光连接池需要配置slf4j日志组件1.7.25版本jar包

Maven Repository: org.slf4j » slf4j-api » 1.7.25 (mvnrepository.com)

slf4j-log4j12-1.5.11.jar 下载

slf4j-log4j12下载 点击直接下载

在这里插入图片描述

为什么配置日志需要这三个呢?详情slf4j-api、slf4j-log4j12、log4j之间关系

在这里插入图片描述

配置文件:

jdbcUrl=jdbc:mysql://localhost:3306/java001
driverClassName=com.mysql.cj.jdbc.Driver
username=root
password=root
maximumPoolSize=30
minimumIdle=10
connectionTimeout=3000
# 数据库连接URL
jdbcUrl=jdbc:mysql://localhost:3306/mydatabase

# 数据库用户名
username=myusername

# 数据库密码
password=mypassword

# 连接池名称
poolName=MyConnectionPool

# 连接池大小
maximumPoolSize=10

# 最小空闲连接数
minimumIdle=5

# 连接超时时间(毫秒)
connectionTimeout=30000

# 空闲连接超时时间(毫秒)
idleTimeout=600000

# 最大生存时间(毫秒)
maxLifetime=1800000

测试代码:

 @Test
public void testHikari() throws SQLException, IOException {
    //1.配置连接池
    HikariConfig hikariConfig = new HikariConfig();
    //也可以通过properties配置文件配置连接池new HikariConfig(Properties  properties)
    //Properties properties = new Properties();
    //FileInputStream fileInputStream = new FileInputStream("src\\hikaricp.properties");
    //properties.load(fileInputStream);
    //HikariConfig hikariConfig = new HikariConfig(properties)
    hikariConfig.setJdbcUrl("jdbc:mysql://localhost:3306");
    hikariConfig.setDriverClassName("com.mysql.cj.jdbc.Driver");
    hikariConfig.setUsername("root");
    hikariConfig.setPassword("root");
    hikariConfig.setMaximumPoolSize(30); // 最大连接数
    hikariConfig.setMinimumIdle(10);     // 最小连接数
    hikariConfig.setConnectionTimeout(3000); // 连接超时时间从连接池中获取一个连接最大等待多久时间,单位毫秒
   
    //2.通过配置类生成HikariCP连接池对象
    HikariDataSource dataSource = new HikariDataSource(hikariConfig);
    System.out.println(dataSource.getConnection());
}

输出结果:

在这里插入图片描述

DBCP

需要下载两个jar包点击直接下载或者去官网

commons-pool2-2.12.0-bin.zip 直接下载

commons-dbcp2-2.11.0-bin.zip 直接下载

官网

Pool – Download Apache Commons Pool

DBCP – Download Apache Commons DBCP

下载完成解压后把这两jar包添加到库中

在这里插入图片描述

在这里插入图片描述

使用过程可能会遇到java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory错误

DBCP需要依赖这个工厂包装类包装日志所以我们还需要下载一个jar包

commons-logging-1.3.0-bin.zip 直接下载

把jar包添加到库

在这里插入图片描述

配置文件dbcp.properties

url=jdbc:mysql://localhost:3306/java001
driverClassName=com.mysql.cj.jdbc.Driver
username=root
password=root
initialSize=10
maxActive=30
maxWait=3000

测试代码:

@Test
public void testDBCP() throws IOException, SQLException {
    // 创建一个Properties对象
    Properties properties = new Properties();
    // 创建一个FileInputStream对象,用于读取src\\dbcp.properties文件
    FileInputStream fileInputStream
        = new FileInputStream("src\\dbcp.properties");
    // 使用FileInputStream对象读取文件,并将文件内容加载到properties对象中
    properties.load(fileInputStream);
    // 使用properties对象创建一个BasicDataSource对象
    BasicDataSource dataSource = BasicDataSourceFactory.createDataSource(properties);
    // 打印dataSource对象创建的连接
    System.out.println(dataSource.getConnection());
}

DBCP和德鲁伊一样也是从工厂包装类创建数据源对象

输出结果:

在这里插入图片描述

性能对比

各个连接池的连接性能对比相同配置

driverClassName = com.mysql.cj.jdbc.Driver
url = jdbc:mysql://localhost:3306/java001?useServerPrepStmts=true
username = root
password = root
initialSize = 10
maxActive = 30
maxWait = 1000

测试代码:

@Test
public void testPerformance() throws Exception {
    // c3p0
    ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
    long start = System.currentTimeMillis();
    for (int i = 0; i < 500; i++) {
        Connection connection = comboPooledDataSource.getConnection();
        connection.close();
    }
    long end = System.currentTimeMillis();
    System.out.println("c3p0 cost: " + (end - start) + " ms");

    // Druid
    Properties properties = new Properties();
    FileInputStream fileInputStream = new FileInputStream("src\\jdbc.properties");
    properties.load(fileInputStream);
    DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
    start = System.currentTimeMillis();
    for (int i = 0; i < 500; i++) {
        Connection connection = dataSource.getConnection();
        connection.close();
    }
    end = System.currentTimeMillis();
    System.out.println("Druid cost: " + (end - start) + " ms");

    // hikaricp
    Properties hikariProperties = new Properties();
    FileInputStream hikariFileInputStream = new FileInputStream("src\\hikaricp.properties");
    hikariProperties.load(hikariFileInputStream);
    HikariConfig hikariConfig = new HikariConfig(hikariProperties);
    HikariDataSource hikariDataSource = new HikariDataSource(hikariConfig);
    start = System.currentTimeMillis();
    for (int i = 0; i < 500; i++) {
        Connection connection = hikariDataSource.getConnection();
        connection.close();
    }
    end = System.currentTimeMillis();
    System.out.println("Hikari cost: " + (end - start)  + "ms");

    // DBCP
    // 创建一个Properties对象
    Properties dbcpProperties = new Properties();
    // 创建一个FileInputStream对象,用于读取src\\dbcp.properties文件
    FileInputStream dbcpFileInputStream
        = new FileInputStream("src\\dbcp.properties");
    properties.load(dbcpFileInputStream);
    BasicDataSource basicDataSource = BasicDataSourceFactory.createDataSource(properties);
    start = System.currentTimeMillis();
    for (int i = 0; i < 500; i++) {
        Connection connection = basicDataSource.getConnection();
        connection.close();
    }
    end = System.currentTimeMillis();
    System.out.println("DBCP cost: " + (end - start) + " ms");
}

输出结果:

在这里插入图片描述
end

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值