zoukankan      html  css  js  c++  java
  • JDBC连接池C3P0

    连接池

       1)传统方式找DriverManager要连接。数目是有限的。 

       2)传统方式的close()。并没有将Connection重用。仅仅是切断应用程序和数据库的桥梁,即无发送到SQL命令到数据库端运行

       3)项目中,对于Connection不说,不会直接使用DriverManager取得,而使用连接池方式。

      4)DBCP和C3P0,都是Java开源的。都必须直接或间接实现javax.sql.DataSource接口

      5)DBCP连接池须要dbcp.properties文件。同一时候需增加3个相应的jar包

     *6)C3P0连接池须要在/WEB-INF/classes/文件夹下存放c3p0-config.xml文件,该类ComboPooledDataSource在创建时

         会自己主动在指定的文件夹下找xml文件,并载入默认设置

       7)重构JdbcUtil类 

     

    DBCP连接池

    l      DBCP 是 Apache 软件基金组织下的开源连接池实现,使用DBCP数据源,应用程序应在系统中添加例如以下两个 jar 文件:

    •        commons-dbcp.jar:连接池的实现

    •        commons-pool.jar: 连接池实现的依赖类

    •        commons-collections.jar :连接池实现的集合类

    l      Tomcat 的连接池正是採用该连接池来实现的。

    #dbcp.properties 配置文件

    driverClassName=com.mysql.jdbc.Driver

    url=jdbc:mysql://127.0.0.1:3306/mydb2

    username=root

    password=root

    关键代码

    static{

           InputStreamin = JdbcUtil.class.getClassLoader().

                         getResourceAsStream("dbcp.properties");

           Propertiesprop = new Properties();

           prop.load(in);

     

           BasicDataSourceFactoryfactory = new BasicDataSourceFactory();

           dataSource = factory.createDataSource(prop);

    }

    实例代码:

    //測试连接池DBCP的使用方法

    publicclass Demo2 {

        publicstaticvoid main(String[] args) throws Exception {

           long begin = System.currentTimeMillis();

           //载入属性文件

           InputStream is = Demo2.class.getClassLoader().getResourceAsStream("dbcp.properties");

           Properties props = new Properties();

           props.load(is);

           //创建DBCP连接池工厂

           BasicDataSourceFactory factory = new BasicDataSourceFactory();

           //创建数据源,即连接池

           DataSource ds = factory.createDataSource(props);

           for(int i=1;i<=50000;i++){

               //从连接池中取得一个空暇的连接对象

               Connection conn = ds.getConnection();

               if(conn!=null){

                  System.out.println(i+":取得连接");

               }

               //将连接对象还回给连接池

               conn.close();

           }

           long end = System.currentTimeMillis();

           System.out.println("共用" + (end-begin)/1000+"");

        }

    }

    c3p0:

    配置文件:

    <?

    xml version="1.0"encoding="UTF-8"?>

    <!-- 文件名称不能乱改,须用默认的c3o0-config.xml -->

    <c3p0-config>

        <default-config>

           <property name="driverClass">com.mysql.jdbc.Driver</property>

           <property name="user">root</property>

           <property name="password">root</property>

           <property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/mydb2</property>

        </default-config>

    </c3p0-config>

     

    /推荐使用c3p0连接池

    //測试连接池C3P0的使用方法

    publicclass Demo3 {

        publicstaticvoid main(String[] args) throws Exception {

           long begin = System.currentTimeMillis();

           //创建C3P0连接池

           ComboPooledDataSource dataSource = new ComboPooledDataSource();

           for(int i=1;i<=100000;i++){

               Connection conn = dataSource.getConnection();

               if(conn!=null){

                  System.out.println(i+":取得连接");

                  conn.close();

               }

           }

           long end = System.currentTimeMillis();

           System.out.println("共用" + (end-begin)/1000+"");

        }

    }

     

     

    JdbcUtil工具类,封装从c3p0的连接池获取连接:

    //JDBC工具类:关闭流和取得连接

    publicfinalclass JdbcUtil3 {

        //数据源

        privatestatic ComboPooledDataSource dataSource;

        static{//静态块。读取c3p0默认配置文件

           dataSource = new ComboPooledDataSource();

        }

        //取得连接

        publicstatic Connection getMySqlConnection() throws SQLException{

           return  dataSource.getConnection();

        }

        //关闭连接

        publicstaticvoid close(Connection conn) throws SQLException{

           if(conn!=null){

               conn.close();

           }

        }

    }

     

    C3P0连接池详细參数说明例如以下:

    c3p0-config>
      <default-config>
     <!--当连接池中的连接耗尽的时候c3p0一次同一时候获取的连接数。Default:3 -->
     <propertyname="acquireIncrement">3</property>
     
     <!--定义在从数据库获取新连接失败后反复尝试的次数。Default: 30 -->
     <property name="acquireRetryAttempts">30</property>
     
     <!--
    两次连接中间隔时间,单位毫秒。Default:1000 -->
     <property name="acquireRetryDelay">1000</property>
     
     <!--
    连接关闭时默认将全部未提交的操作回滚。Default:false -->
     <propertyname="autoCommitOnClose">false</property>
     
     <!--c3p0将建一张名为Test的空表,并使用其自带的查询语句进行測试。

    假设定义了这个參数那么
      
    属性preferredTestQuery将被忽略。

    你不能在这张Test表上进行不论什么操作,它将仅仅供c3p0測试
      
    使用。Default:null-->
     <propertyname="automaticTestTable">Test</property>

     

     <!--获取连接失败将会引起全部等待连接池来获取连接的线程抛出异常。可是数据源仍有效
      
    保留。并在下次调用getConnection()的时候继续尝试获取连接。

    假设设为true,那么在尝试
      
    获取连接失败后该数据源将申明已断开并永久关闭。Default: false-->
     <property name="breakAfterAcquireFailure">false</property>

     

     <!--当连接池用完时client调用getConnection()后等待获取新连接的时间,超时后将抛出
      SQLException,
    如设为0则无限期等待。单位毫秒。

    Default: 0 --> 
     <property name="checkoutTimeout">100</property>

     

     <!--通过实现ConnectionTesterQueryConnectionTester的类来測试连接。类名需制定全路径。


      Default: com.mchange.v2.c3p0.impl.DefaultConnectionTester-->

     <propertyname="connectionTesterClassName"></property>

     

     <!--指定c3p0 libraries的路径,假设(通常都是这样)在本地就可以获得那么无需设置。默认null就可以
      Default: null-->

     <propertyname="factoryClassLocation">null</property>

     

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

     

     <!--60秒检查全部连接池中的空暇连接。Default: 0 --> 
     <property name="idleConnectionTestPeriod">60</property>

     

     <!--初始化时获取三个连接,取值应在minPoolSizemaxPoolSize之间。Default: 3 --> 
     <property name="initialPoolSize">3</property>
     
     <!--最大空暇时间,60秒内未使用则连接被丢弃。

    若为0则永不丢弃。

    Default: 0 -->
     <propertyname="maxIdleTime">60</property>
     
     <!--
    连接池中保留的最大连接数。Default:15 -->
     <property name="maxPoolSize">15</property>
     
     <!--JDBC的标准參数。用以控制数据源内载入的PreparedStatements数量。但因为预缓存的statements
      
    属于单个connection而不是整个连接池。

    所以设置这个參数须要考虑到多方面的因素。
      
    假设maxStatementsmaxStatementsPerConnection均为0。则缓存被关闭。Default: 0-->
     <property name="maxStatements">100</property>
     
     <!--maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数。Default: 0  -->
     <propertyname="maxStatementsPerConnection"></property>

     

     <!--c3p0是异步操作的,缓慢的JDBC操作通过帮助进程完毕。扩展这些操作能够有效的提升性能
      
    通过多线程实现多个操作同一时候被运行。

    Default:3--> 
     <property name="numHelperThreads">3</property>

     

     <!--当用户调用getConnection()时使root用户成为去获取连接的用户。

    主要用于连接池连接非c3p0
      
    的数据源时。Default:null--> 
     <propertyname="overrideDefaultUser">root</property>
     
     <!--overrideDefaultUser參数相应使用的一个參数。Default:null-->
     <property name="overrideDefaultPassword">password</property>

     

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

     

     <!--定义全部连接測试都运行的測试语句。在使用连接測试的情况下这个一显著提高測试速度。

    注意:
      
    測试的表必须在初始数据源的时候就存在。Default:null-->
     <propertyname="preferredTestQuery">select id from test whereid=1</property>

     

     <!--用户改动系统配置參数运行前最多等待300秒。

    Default: 300 --> 
     <property name="propertyCycle">300</property>
     
     
    <!--因性能消耗大请仅仅在须要的时候使用它。假设设为true那么在每一个connection提交的
      
    时候都将校验其有效性。建议使用idleConnectionTestPeriodautomaticTestTable
      
    等方法来提升连接測试的性能。

    Default:false -->
     <propertyname="testConnectionOnCheckout">false</property>
     
     <!--假设设为true那么在取得连接的同一时候将校验连接的有效性。

    Default:false -->
     <propertyname="testConnectionOnCheckin">true</property>

     

     <!--username。Default: null-->
     <propertyname="user">root</property>

     

     <!--早期的c3p0版本号对JDBC接口採用动态反射代理。在早期版本号用途广泛的情况下这个參数
      
    同意用户恢复到动态反射代理以解决不稳定的故障。

    最新的非反射代理更快而且已经開始
      
    广泛的被使用,所以这个參数未必实用。如今原先的动态反射与新的非反射代理同一时候受到
      
    支持,但今后可能的版本号可能不支持动态反射代理。Default: false-->
     <propertyname="usesTraditionalReflectiveProxies">false</property>


        <property name="automaticTestTable">con_test</property>
        <propertyname="checkoutTimeout">30000</property>
        <propertyname="idleConnectionTestPeriod">30</property>
        <propertyname="initialPoolSize">10</property>
        <propertyname="maxIdleTime">30</property>
        <propertyname="maxPoolSize">25</property>
        <propertyname="minPoolSize">10</property>
        <propertyname="maxStatements">0</property>

        <user-overrides user="swaldman">
        </user-overrides>

      </default-config>
      <named-config name="dumbTestConfig">
        <propertyname="maxStatements">200</property>
        <user-overrides user="poop">
          <propertyname="maxStatements">300</property>
        </user-overrides>
       </named-config>
    </c3p0-config>

  • 相关阅读:
    职业规划 !!
    linux上ssh配置指南
    低内存VPS用轻量级的Dropbear替换OpenSSH
    修改shell终端提示信息
    减少windows7内存占用的优化方案(内存占用才285兆 比XP还省)
    linux下提示符修改
    mysql存储过程学习笔记区块,条件,循环
    Apache下实现禁止目录浏览
    [学习指导] linux 启动过程以及 /etc/rc.d/init.d/目录的一点理解
    mysql 5.0存储过程学习总结
  • 原文地址:https://www.cnblogs.com/zhchoutai/p/7080991.html
Copyright © 2011-2022 走看看