C3P0连接池

一、c3p0简介:

数据库连接池的基本思想就是为数据库连接建立一个“缓冲池”。预先在缓冲池中放入一定数量的连接,当需要建立数据库连接时,只需从“缓冲池”中取出一个,使用完毕之后再放回去。我们可以通过设定连接池最大连接数来防止系统无尽的与数据库连接。

获取一个连接,系统要在背后做很多消耗资源的事情,大多时候,创建连接的时间比执行sql语句的时间还要长。
用户每次请求都需要向数据库获得链接,而数据库创建连接通常需要消耗相对较大的资源,创建时间也较长。

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

c3p0是一个开源的JDBC连接池,它实现了数据源和JNDI绑定,支持JDBC3规范和JDBC2的标准扩展。c3p0一般是与Hibernate,Spring等框架一块使用的,当然也可以单独使用。
dbcp没有自动回收空闲连接的功能,c3p0有自动回收空闲连接功能。

二、c3p0的使用和配置:

导入jar文件:前2个是c3p0的jar包,后一个是jdbc的jar包

 

 

配置:在src下建立一个xml文件,命名为c3p0-config.xml   命名不能改其他的,否则找不到

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>    
        <default-config>    
            <property name="jdbcUrl">jdbc:mysql://localhost:3306/mydb</property>    <!-- jdbc协议地址 -->
            <property name="driverClass">com.mysql.jdbc.Driver</property>             <!-- 驱动 -->
            <property name="user">root</property>                                     <!-- 数据库的用户名  -->
            <property name="password"></property>                                     <!-- 数据库密码 ,若没有密码,该项可省略 -->
        
      <!--***** *************************以下property 配置可不写, 有默认值***************************************** -->
      
            <property name="initialPoolSize">10</property>                    <!-- 初始化时的链接数量 -->
            <property name="maxPoolSize">100</property>                        <!-- 最大链接数量 -->
            <property name="minPoolSize">10</property>                        <!-- 最小链接数量  -->
            
            <!--当连接池中的连接耗尽的时候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>    
      
    <!--早期的c3p0版本对JDBC接口采用动态反射代理。在早期版本用途广泛的情况下这个参数    
    允许用户恢复到动态反射代理以解决不稳定的故障。最新的非反射代理更快并且已经开始    
    广泛的被使用,所以这个参数未必有用。现在原先的动态反射与新的非反射代理同时受到    
    支持,但今后可能的版本可能不支持动态反射代理。Default: false-->    
    <property name="usesTraditionalReflectiveProxies">false</property>  
            
        </default-config>    
    </c3p0-config>

 

 

完成以上配置,我们来建立一个类Test  来测试一下,在使用c3p0的情况下和不使用的情况下,究竟效率差了多少

package com.maya.test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Calendar;
import com.mchange.v2.c3p0.ComboPooledDataSource;



public class Test {

    //使用jdbc方式链接
    public static void main111(String[] args) throws Exception {        
        long x=Calendar.getInstance().getTimeInMillis();        //获取链接之前,的时间
        
        for(int i=0;i<1000;i++){
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","root","");
            conn.close();                //这里也是打开一次之后就关闭一次
        }
        long y=Calendar.getInstance().getTimeInMillis();
        System.out.println("jdbc链接方式需要的时间是  "+(y-x));        //最后打印一下完成整个循环所需要的时间      
        
    }
    
    //使用c3p0连接池
    public static void main(String[] args) throws Exception {
        long x=Calendar.getInstance().getTimeInMillis();    //获取链接之前,的时间
        
        ComboPooledDataSource ds=new ComboPooledDataSource();    //读取xml文件的配置
        
        for(int i=0;i<1000;i++){                            //循环1000次,即打开链接,关闭链接1000次
            Connection conn=ds.getConnection();
            conn.close();
        }
        long y=Calendar.getInstance().getTimeInMillis();    //循环完成后的时间
        System.out.println("c3p0连接池需要的时间是:  "+(y-x));                            //最后打印一下完成整个循环所需要的时间      
        
    }

}

这里因为没有导入junit    jar包,我直接写了一个main函数来测试得到的结果如下:

很明显,在效率方面,完胜。

 

Hibernate框架中,使用连接池:

在hibernate框架中,使用链接池的效果,并不是特别的明显,整体来说,效率并没有过多的提升,步骤同上,导入jar包,hibernate需要额外一个jar包,在hibernate/lib/optional/c3p0文件夹下    找到hibernate-c3p0-5.2.6.final.jar文件

 

配置时,需要在hibernate.cfg.xml文件中配置

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
            <!--c3p0需要的配置 -->
        <property name="hibernate.connection.provider_class">org.hibernate.c3p0.internal.C3P0ConnectionProvider</property>
        <property name="hibernate.c3p0.min_size">1</property>
        <property name="hibernate.c3p0.max_size">10</property>
        
        <!--  以下是hibernate框架的配置    -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydb</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        
        <mapping resource="com/itnba/maya/entities/Family.hbm.xml"/>
        <mapping resource="com/itnba/maya/entities/Info.hbm.xml"/>
        <mapping resource="com/itnba/maya/entities/Work.hbm.xml"/>
        <mapping resource="com/itnba/maya/entities/Nation.hbm.xml"/>
        <mapping resource="com/itnba/maya/entities/Title.hbm.xml"/>
        
    </session-factory>
</hibernate-configuration>

 

做一个测试类,测试一下效果

package com.itnba.maya.test;

import java.util.Calendar;
import java.util.List;

import org.hibernate.Session;

import com.itnba.maya.entities.Info;

public class TestHibernate {

    public static void main(String[] args) {
        
        long start = Calendar.getInstance().getTimeInMillis();    //读取开始执行时的时间
        
        for(int i=0;i<1000;i++){
            Session session = HibernateUtil.getSession();
            List<Info> list = session.createQuery("from Info").getResultList();
            for(Info data:list){
                System.out.println(data);
            }
            HibernateUtil.closeSession();
        }
        long end = Calendar.getInstance().getTimeInMillis();//读取结束执行时的时间
        
        System.out.println(end-start);                        //打印执行期间所花的时间

    }

}

最后发现,hibernate中,加和不加,区别并不是很多,因为在hibernate中,session会话要保证单例模式。

 

spring中如何使用c3p0呢?

同上,导包,c3p0的jar包,另外还需要的是spring的jar包

配置:有两种方法,一种是利用properties系统文件配置,一种是spring配置文件配置

 

1.spring配置文件:

在src下建立bean.xml    bean这个名字可以用其他的

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">

    <!--  c3p0的配置 -->
    <bean class="com.mchange.v2.c3p0.ComboPooledDataSource" id="combo">
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mydb?characterEncoding=GBK"></property>
        <property name="user" value="root"></property>
        <property name="password" value=""></property>
        <property name="minPoolSize" value="3"></property>
        <property name="maxPoolSize" value="20"></property>
    </bean>
    
</beans>

 

 

建一个测试类test测试一下配置是否成功

package com.maya.test;

import java.sql.Connection;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class Test {
    

    
    public static void main(String[] args) throws Exception{
    
        ApplicationContext app= new ClassPathXmlApplicationContext("beans.xml");    //读取配置
        
        ComboPooledDataSource ds=(ComboPooledDataSource)app.getBean("combo");        //获取id为combo的的配置
        
        Connection conn=ds.getConnection();                        //转换成 java.sql.Connection
        
        System.out.println(conn.isClosed());        //最后打印一下,看看链接是否是关闭状态,false为未关闭,即打开
        conn.close();
        
    }

}

     表示,链接打开了,配置完成

 

第二种方式

  properties系统文件配置

  建立一个db.properties 系统文件

driverClass=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/mydb?characterEncoding=GBK
user=root
password=

minPoolSize=5
maxPoolSize=15
initialPoolSize=5

然后在spring配置文件中,

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
    <!--  获取系统文件中的数据-->
    <context:property-placeholder location="classpath:db.properties"/>
        <!-- 用EL表达式获取系统文件中的属性-->
    <bean class="com.mchange.v2.c3p0.ComboPooledDataSource" id="combo">
        <property name="driverClass" value="${driverClass}"></property>
        <property name="jdbcUrl" value="${jdbcUrl}"></property>
        <property name="user" value="${user}"></property>
        <property name="password" value="${password}"></property>
        
        <property name="minPoolSize" value="${minPoolSize}"></property>
        <property name="maxPoolSize" value="${maxPoolSize}"></property>
        <property name="initialPoolSize" value="${initialPoolSize}"></property>
    </bean>
    
</beans>

 

测试结果,同上

posted @ 2017-03-29 21:17  赵天成123  阅读(1637)  评论(0编辑  收藏  举报