数据库连接池之C3P0

JAVA学习网 2018-12-24 22:13:06

一、C3P0的使用步骤

1:导入相关的依赖jar包

  c3p0-0.9.5.2.jar
  mchange-commons-java-0.2.12.jar

2:代码实现

  • A:硬编码的实现方式

 

package com.dreambamboo.test;

import com.mchange.v2.c3p0.ComboPooledDataSource;


import javax.lang.model.element.NestingKind;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class C3P0Test {
    public static void main(String[] args) {
        try {
            ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
            comboPooledDataSource.setDriverClass("com.mysql.jdbc.Driver");
            comboPooledDataSource.setUser("root");
            comboPooledDataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
            comboPooledDataSource.setPassword("mysql");
            Connection connection = comboPooledDataSource.getConnection();
            Statement statement = connection.createStatement();
            String sql = "select * from student where id = 2";
            ResultSet rs = statement.executeQuery(sql);
            if (rs.next()){
                System.out.println(rs.getInt("id") + "==============>" + rs.getString("name"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
    }
}
View Code

 

  • B:软编码实现方式

    • a:借助c3p0工具类实现

      • c3p0工具类

package com.dreambamboo.utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class C3P0Utils {
    private static  final ComboPooledDataSource DATA_SOURCE = new ComboPooledDataSource("dumbTestConfig");
    private static Connection connection = null;

    /**
     * 获取数据库连接connection
     * @return
     */
    public static Connection getConnection(){
        try {
            connection = DATA_SOURCE.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    /**
     * 释放资源
     * @param connection
     * @param statement
     * @param resultSet
     */
    public void release(Connection connection, Statement statement, ResultSet resultSet){
        try {
            if (connection != null) {
                connection.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (resultSet != null) {
                resultSet.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
View Code
      • 测试代码

package com.dreambamboo.test;

import com.dreambamboo.utils.C3P0Utils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Test03 {
    public static void main(String[] args) {
        Connection connection = C3P0Utils.getConnection();
        try {
            Statement statement = connection.createStatement();
            String sql = "select * from student";
            ResultSet resultSet = statement.executeQuery(sql);
            while (resultSet.next()){
                System.out.println(resultSet.getInt("id") + "===========>>>>>>>" + resultSet.getString("name"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
}
View Code
      • 运行效果

    • b:借助c3p0配置文件实现

      • c3p0配置文件(简单版本只配置数据源)

<?xml version="1.0" encoding="UTF-8" ?>
<c3p0-config>
    <named-config name="dumbTestConfig">
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/test</property>
        <property name="user">root</property>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="password">mysql</property>
    </named-config>
</c3p0-config>
View Code
      • 测试代码

package com.dreambamboo.test;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class C3P0ConfigTest {
    public static void main(String[] args) {
        //dumbTestConfig为配置文件中的<named-config name="dumbTestConfig">的name的值
        ComboPooledDataSource dataSource = new ComboPooledDataSource("dumbTestConfig");
        try {
            Connection connection = dataSource.getConnection();
            Statement statement = connection.createStatement();
            String sql = "select * from student";
            ResultSet resultSet = statement.executeQuery(sql);
            while (resultSet.next()){
                System.out.println(resultSet.getInt("id") + "==============>>>>>>>>>>" + resultSet.getString("name"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
View Code
      • 运行效果

二、C3P0配置详解

1、数据源的配置

参数 默认值 说明
driverClass 数据库驱动
jdbcUrl jdbc数据库连接地址
user 数据库用户名
password 登陆数据库的密码

    常用的数据库驱动简介

      A:Oracle

      • 驱动:oracle.jdbc.driver.OracleDriver
      • url:jdbc:oracle:thin:@dbip:port:databasename
        • url各部分的含义
          •  dbip –为数据库服务器的IP地址,如果是本地可写:localhost或127.0.0.1。
          •  port –为数据库的监听端口,需要看安装时的配置,缺省为1521。
          •  databasename –为数据库的SID,通常为全局数据库的名字。            

      B:MySQL

      • 驱动:com.mysql.jdbc.Driver
      • url:jdbc:mysql://dbip:port/databasename
        • url各部分的含义
          •  dbip –为数据库服务器的IP地址,如果是本地可写:localhost或127.0.0.1。
          •  port –为数据库的监听端口,需要看安装时的配置,缺省为3306。
          •  databasename –为数据库的SID,通常为全局数据库的名字。 

      C:SQLServer

      • 驱动:com.microsoft.jdbc.sqlserver.SQLServerDriver
      • url:jdbc:microsoft:sqlserver://dbip:port;DatabaseName=databasename
        • url各部分的含义
          • dbip –为数据库服务器的IP地址,如果是本地可写:localhost或127.0.0.1。
          • port –为数据库的监听端口,需要看安装时的配置,缺省为1433。
          • databasename –为数据库的SID,通常为全局数据库的名字。 

2、连接池的基础配置

参数 默认值 说明
initialPoolSize 3 连接池初始化时创建的连接数(结余maxPoolSize和minPoolSize之间)
maxPoolSize 15 连接池中拥有的最大连接数,如果获得新连接时会是连接总数超过这个值则不会在获取新的连接,而是等待其他连接释放,所以这个值可能会设置很大
minPoolSize 3 连接池保持的最小连接数,后面的maxIdeTimeExcessConnections跟这个配合使用来减轻连接池的负载
acquireIncrement 3 连接池在无空闲连接时一次性创建的新数据库连接数

 

3、管理池大小和连接时间的配置

参数 默认值 说明
maxIdleTime 0 不会断开连接
maxConnectorAge 0 连接的最大最对年龄,单位是秒,0表示绝对年龄无限大
maxIdleTimeExcessConnection 0 单位秒,为了减轻连接池的负载,当连接池经过数据访问高峰创建了很多连接,但是后面的连接池不需要维护这么多连接,必须小于maxIdleTime。配置不为0,则将连接吃的数量保持到minPoolSize

 

4、配置连接测试

参数 默认值 说明
automaticTestTable  null 如果不为null,c3p0姜程程指定名称的空表,使用该表来测试连接 。
connectionTesterClassName com.mchange.v2.c3p0.impl.DefaultConnectionTester  通过实现ConnectionTester或QueryConnectionTester的类来测试连接,类名需指定全路径 
idleConnectinoTestPeriod 每隔几秒检查所有连接池中的空闲连接 
preferredTestQuery null  定义所有连接测试都执行的测试语句,在使用连接测试的情况下这个会显著提高测试速度。注意:测试的表必须在初始数据源的时候就存在
 testConnectionOnCheckin false  如果设为true那么在取得连接的同时将校验连接的有效性 
 testConnectionOnCheckout  false  如果为true,在连接释放的同时将校验连接的有效性 

    在这几个参数中,idleConnectionTestPeriod、testConnectionOnCheckout和testConnectionOnCheckin控制什么时候连接将被校验检测,automaticTestTable、connectionTesterClassName、和preferedTestQuery控制连接将怎么样被检测。

5、语句池的配置

参数 默认值 说明
maxStatements 0 JDBC的标准参数,用以控制数据源内健在的PreparedStatements数量
maxStatementsPerConnection 0 maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数
statementCacheNumDeferredCloseThreads 0 如果大于零,则语句池将延迟物理close()缓存语句直到其父连接未被任何客户端使用,或者在其内部(例如在测试中)由池本身使用

 

6、数据库中断恢复的配置

参数 默认值 说明
acquireRetryAttempts 30 定义在从数据库获取新连接失败后重复尝试的次数
acquireRetryDelay 1000 两次连接间隔时间,单位毫秒
breakAfterAcquireFailure false 获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常,但是数据源仍有效保留,并在下次调用getConnection()的时候继续尝试获取连接,如果设为true,那么在尝试获取连接失败后该数据源将申明已断开并永久关闭

 

7、未解决的事务处理的配置

参数 默认值 说明
autoCommitOnClose false 连接关闭时默认将所有未提交的操作回滚,如果为true,则未提交设置为待提交而不是回滚
forceIgnoreUnresolvedTransactions false 官方文档建议不要设置为true

 

 

8、其他数据源配置

参数 默认值 说明
checkoutTimeout 0 当连接池用完时客户端调用getConnection()后等待获取新连接的时间,超时后将抛出SQLException,如果设置为0,则无限期等待,单位毫秒
factoryClassLocation 0

指定c3p0 libraries的路径,如果(通常都是这样)在本地即可获得,无需设置,默认null即可

numHelperThreads 3

c3p0是异步操作的,缓慢的JDBC操作通过帮助进程完成,扩展这些操作可以有效的提升性能,通过多线程实现多个操作同时被执行。

三、C3P0的详细配置介绍

<c3p0-config> 
<default-config> 
<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 --> 
<property name="acquireIncrement">3</property> 

<!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 --> 
<property name="acquireRetryAttempts">30</property> 

<!--两次连接中间隔时间,单位毫秒。Default: 1000 --> 
<property name="acquireRetryDelay">1000</property> 

<!--连接关闭时默认将所有未提交的操作回滚。Default: false --> 
<property name="autoCommitOnClose">false</property> 

<!--c3p0将建一张名为Test的空表,并使用其自带的查询语句进行测试。如果定义了这个参数那么 
属性preferredTestQuery将被忽略。你不能在这张Test表上进行任何操作,它将只供c3p0测试 
使用。Default: null--> 
<property name="automaticTestTable">Test</property> 

<!--获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效 
保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试 
获取连接失败后该数据源将申明已断开并永久关闭。Default: false--> 
<property name="breakAfterAcquireFailure">false</property> 

<!--当连接池用完时客户端调用getConnection()后等待获取新连接的时间,超时后将抛出 
SQLException,如设为0则无限期等待。单位毫秒。Default: 0 --> 
<property name="checkoutTimeout">100</property> 

<!--通过实现ConnectionTester或QueryConnectionTester的类来测试连接。类名需制定全路径。 
Default: com.mchange.v2.c3p0.impl.DefaultConnectionTester--> 
<property name="connectionTesterClassName"></property> 

<!--指定c3p0 libraries的路径,如果(通常都是这样)在本地即可获得那么无需设置,默认null即可 
Default: null--> 
<property name="factoryClassLocation">null</property> 

<!--Strongly disrecommended. Setting this to true may lead to subtle and bizarre bugs. 
(文档原文)作者强烈建议不使用的一个属性--> 
<property name="forceIgnoreUnresolvedTransactions">false</property> 

<!--每60秒检查所有连接池中的空闲连接。Default: 0 --> 
<property name="idleConnectionTestPeriod">60</property> 

<!--初始化时获取三个连接,取值应在minPoolSize与maxPoolSize之间。Default: 3 --> 
<property name="initialPoolSize">3</property> 

<!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 --> 
<property name="maxIdleTime">60</property> 

<!--连接池中保留的最大连接数。Default: 15 --> 
<property name="maxPoolSize">15</property> 

<!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements 
属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。 
如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0--> 
<property name="maxStatements">100</property> 

<!--maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数。Default: 0 --> 
<property name="maxStatementsPerConnection"></property> 

<!--c3p0是异步操作的,缓慢的JDBC操作通过帮助进程完成。扩展这些操作可以有效的提升性能 
通过多线程实现多个操作同时被执行。Default: 3--> 
<property name="numHelperThreads">3</property> 

<!--当用户调用getConnection()时使root用户成为去获取连接的用户。主要用于连接池连接非c3p0 
的数据源时。Default: null--> 
<property name="overrideDefaultUser">root</property> 

<!--与overrideDefaultUser参数对应使用的一个参数。Default: null--> 
<property name="overrideDefaultPassword">password</property> 

<!--密码。Default: null--> 
<property name="password"></property> 

<!--定义所有连接测试都执行的测试语句。在使用连接测试的情况下这个一显著提高测试速度。注意: 
测试的表必须在初始数据源的时候就存在。Default: null--> 
<property name="preferredTestQuery">select id from test where id=1</property> 

<!--用户修改系统配置参数执行前最多等待300秒。Default: 300 --> 
<property name="propertyCycle">300</property> 

<!--因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection提交的 
时候都将校验其有效性。建议使用idleConnectionTestPeriod或automaticTestTable 
等方法来提升连接测试的性能。Default: false --> 
<property name="testConnectionOnCheckout">false</property> 

<!--如果设为true那么在取得连接的同时将校验连接的有效性。Default: false --> 
<property name="testConnectionOnCheckin">true</property> 

<!--用户名。Default: null--> 
<property name="user">root</property> 

在Hibernate(spring管理)中的配置:
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
  <property name="driverClass"><value>oracle.jdbc.driver.OracleDriver</value></property>
  <property name="jdbcUrl"><value>jdbc:oracle:thin:@localhost:1521:Test</value></property>
  <property name="user"><value>Kay</value></property>
  <property name="password"><value>root</value></property>
  <!--连接池中保留的最小连接数。-->            
    <property name="minPoolSize" value="10" />        
    <!--连接池中保留的最大连接数。Default: 15 -->         
    <property name="maxPoolSize" value="100" />        
    <!--最大空闲时间,1800秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->               
    <property name="maxIdleTime" value="1800" />        
    <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->               
    <property name="acquireIncrement" value="3" />         
    <property name="maxStatements" value="1000" />          
    <property name="initialPoolSize" value="10" />          
    <!--每60秒检查所有连接池中的空闲连接。Default: 0 -->       
    <property name="idleConnectionTestPeriod" value="60" />          
    <!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 -->       
    <property name="acquireRetryAttempts" value="30" />          
    <property name="breakAfterAcquireFailure" value="true" />              
    <property name="testConnectionOnCheckout" value="false" /> 
 </bean>
View Code
阅读(7606) 评论(0)