C3P0连接池配置和实现详解


C3P0连接池配置和实现详解

===================================================================


2016年netty/mina/java nio视频教程java游戏服务器设计教程

互联网架构师教程: http://blog.csdn.net/pplcheer/article/details/71887910

互联网架构师视频课程 Dubbo ActiveMQ spring Netty MongoDB Jvm :http://blog.csdn.net/pplcheer/article/details/72794970

需要的加qq:1225462853,备注:程序员学习视频

其他视频都可以索要(Netty   NET    C++ 等等)

===================================================================


一、C3P0配置
c3p0的配置方式分为三种,分别是
1.setters一个个地设置各个配置项
2.类路径下提供一个c3p0.properties文件
3.类路径下提供一个c3p0-config.xml文件


1. setters一个个地设置各个配置项
这种方式最繁琐,形式一般是这样:

  1. <span style="font-size: 14px;">    Properties props = new Properties();    
  2.     InputStream in = ConnectionManager.class.getResourceAsStream("/c3p0.properties");    
  3.     props.load(in);    
  4.     in.close();    
  5.         
  6.     ComboPooledDataSource cpds = new ComboPooledDataSource();    
  7.     cpds.setDriverClass(props.getProperty("driverClass"));    
  8.     cpds.setJdbcUrl(props.getProperty("jdbcUrl"));    
  9.     cpds.setUser(props.getProperty("user"));    
  10.     cpds.setPassword(props.getProperty("password"));  </span>  
    Properties props = new Properties();  
    InputStream in = ConnectionManager.class.getResourceAsStream("/c3p0.properties");  
    props.load(in);  
    in.close();  
      
    ComboPooledDataSource cpds = new ComboPooledDataSource();  
    cpds.setDriverClass(props.getProperty("driverClass"));  
    cpds.setJdbcUrl(props.getProperty("jdbcUrl"));  
    cpds.setUser(props.getProperty("user"));  
    cpds.setPassword(props.getProperty("password"));  

2. 使用xml方式(名称为c3p0-config.xml)

  1. <span style="font-size: 14px;">    <?xml version="1.0" encoding="UTF-8"?>    
  2.     <c3p0-config>    
  3.         <default-config>    
  4.             <property name="jdbcUrl">jdbc:mysql://localhost:3306/tv_guide    
  5.             </property>    
  6.             <property name="driverClass">com.mysql.jdbc.Driver</property>    
  7.             <property name="user">root</property>    
  8.             <property name="password">root</property>    
  9.         
  10.             <property name="checkoutTimeout">30000</property>    
  11.             <property name="idleConnectionTestPeriod">30</property>    
  12.             <property name="initialPoolSize">10</property>    
  13.             <property name="maxIdleTime">30</property>    
  14.             <property name="maxPoolSize">100</property>    
  15.             <property name="minPoolSize">10</property>    
  16.             <property name="maxStatements">200</property>    
  17.         </default-config>    
  18.     </c3p0-config>  </span>  
    <?xml version="1.0" encoding="UTF-8"?>  
    <c3p0-config>  
        <default-config>  
            <property name="jdbcUrl">jdbc:mysql://localhost:3306/tv_guide  
            </property>  
            <property name="driverClass">com.mysql.jdbc.Driver</property>  
            <property name="user">root</property>  
            <property name="password">root</property>  
      
            <property name="checkoutTimeout">30000</property>  
            <property name="idleConnectionTestPeriod">30</property>  
            <property name="initialPoolSize">10</property>  
            <property name="maxIdleTime">30</property>  
            <property name="maxPoolSize">100</property>  
            <property name="minPoolSize">10</property>  
            <property name="maxStatements">200</property>  
        </default-config>  
    </c3p0-config>  

3、使用properties方式(名称为c3p0.properties)

  1. <span style="font-size: 14px;">    c3p0.jdbcUrl=jdbc:mysql://localhost:3306/tv_guide    
  2.     c3p0.driverClass=com.mysql.jdbc.Driver    
  3.     c3p0.user=root    
  4.     c3p0.password=root    
  5.         
  6.     c3p0.acquireIncrement=3     
  7.     c3p0.idleConnectionTestPeriod=60        
  8.     c3p0.initialPoolSize=10     
  9.     c3p0.maxIdleTime=60     
  10.     c3p0.maxPoolSize=20     
  11.     c3p0.maxStatements=100      
  12.     c3p0.minPoolSize=5    </span>  
    c3p0.jdbcUrl=jdbc:mysql://localhost:3306/tv_guide  
    c3p0.driverClass=com.mysql.jdbc.Driver  
    c3p0.user=root  
    c3p0.password=root  
      
    c3p0.acquireIncrement=3   
    c3p0.idleConnectionTestPeriod=60      
    c3p0.initialPoolSize=10   
    c3p0.maxIdleTime=60   
    c3p0.maxPoolSize=20   
    c3p0.maxStatements=100    
    c3p0.minPoolSize=5    

使用这两种方式进行配置时,只要将配置好的文件放入classpath文件夹下即可,在java代码当中不用显示的给出访问配置方式的代码,c3p0会自动识别!


如果想把配置文件放在自己想放得地方只需设置系统属性:

  1. <span style="font-size: 14px;">System.setProperty("com.mchange.v2.c3p0.cfg.xml","classloader:/resources/c3p0-config.xml");</span>  
System.setProperty("com.mchange.v2.c3p0.cfg.xml","classloader:/resources/c3p0-config.xml");

具体实现代码如下:

  1. <span style="font-size: 14px;">package com.ppl.test;  
  2.   
  3. import java.sql.Connection;  
  4. import java.sql.SQLException;  
  5.   
  6. import org.junit.Test;  
  7.   
  8. import com.ppl.tools.JdbcUtils;  
  9.   
  10. /** 
  11.  * JdbcUtils用来获取Connection * 底层使用了c3p0连接池! * 还需要mysql驱动 
  12.  *  
  13.  * @author pplsunny 
  14.  * 
  15.  */  
  16. public class JdbcUtilsTest {  
  17.     /** 
  18.      * 底层使用了c3p0连接池,说明我们还要提供c3p0配置文件 
  19.      *  
  20.      * @throws SQLException 
  21.      */  
  22.     @Test  
  23.     public void testGetConnection() throws SQLException {  
  24.   
  25.         // System.setProperty("com.mchange.v2.c3p0.cfg.xml","classloader:/resources/c3p0-config.xml");  
  26.   
  27.         // System.setProperty("com.mchange.v2.c3p0.cfg.xml",System.getProperty("user.dir")+"/WebContent/WEB-INF/c3p0-config.xml");  
  28.         System.setProperty("com.mchange.v2.c3p0.cfg.xml", System.getProperty("user.dir") + "/A/c3p0-config.xml");  
  29.   
  30.         String aa = System.getProperty("user.dir");  
  31.         System.out.println("=======" + aa);  
  32.         ;  
  33.         Connection con = JdbcUtils.getConnection();  
  34.         System.out.println(con);  
  35.         JdbcUtils.releaseConnection(con);  
  36.         System.out.println(con.isClosed());  
  37.     }  
  38. }  
  39. </span>  
package com.ppl.test;

import java.sql.Connection;
import java.sql.SQLException;

import org.junit.Test;

import com.ppl.tools.JdbcUtils;

/**
 * JdbcUtils用来获取Connection * 底层使用了c3p0连接池! * 还需要mysql驱动
 * 
 * @author pplsunny
 *
 */
public class JdbcUtilsTest {
	/**
	 * 底层使用了c3p0连接池,说明我们还要提供c3p0配置文件
	 * 
	 * @throws SQLException
	 */
	@Test
	public void testGetConnection() throws SQLException {

		// System.setProperty("com.mchange.v2.c3p0.cfg.xml","classloader:/resources/c3p0-config.xml");

		// System.setProperty("com.mchange.v2.c3p0.cfg.xml",System.getProperty("user.dir")+"/WebContent/WEB-INF/c3p0-config.xml");
		System.setProperty("com.mchange.v2.c3p0.cfg.xml", System.getProperty("user.dir") + "/A/c3p0-config.xml");

		String aa = System.getProperty("user.dir");
		System.out.println("=======" + aa);
		;
		Connection con = JdbcUtils.getConnection();
		System.out.println(con);
		JdbcUtils.releaseConnection(con);
		System.out.println(con.isClosed());
	}
}


二.C3P0连接池封装类

  1. <span style="font-size: 14px;">package com.ppl.tools;  
  2.   
  3. import java.sql.Connection;  
  4. import java.sql.SQLException;  
  5.   
  6. import javax.sql.DataSource;  
  7.   
  8. import com.mchange.v2.c3p0.ComboPooledDataSource;  
  9.   
  10. /** 
  11.  * 使用本类的方法,必须提供c3p0-copnfig.xml文件 
  12.  * @author pplsunny 
  13.  */  
  14. public class JdbcUtils {  
  15.       
  16.     // 饿汉式  
  17.     private static DataSource ds = new ComboPooledDataSource();  
  18.       
  19.     /** 
  20.      * 它为null表示没有事务 
  21.      * 它不为null表示有事务 
  22.      * 当开启事务时,需要给它赋值 
  23.      * 当结束事务时,需要给它赋值为null 
  24.      * 并且在开启事务时,让dao的多个方法共享这个Connection 
  25.      */  
  26.     private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();  
  27.       
  28.     public static DataSource getDataSource() {  
  29.         return ds;  
  30.     }  
  31.       
  32.     /** 
  33.      * dao使用本方法来获取连接 
  34.      * @return 
  35.      * @throws SQLException 
  36.      */  
  37.     public static Connection getConnection() throws SQLException {  
  38.         /* 
  39.          * 如果有事务,返回当前事务的con 
  40.          * 如果没有事务,通过连接池返回新的con 
  41.          */  
  42.         Connection con = tl.get();//获取当前线程的事务连接  
  43.         if(con != nullreturn con;  
  44.         return ds.getConnection();  
  45.     }  
  46.       
  47.     /** 
  48.      * 开启事务 
  49.      * @throws SQLException  
  50.      */  
  51.     public static void beginTransaction() throws SQLException {  
  52.         Connection con = tl.get();//获取当前线程的事务连接  
  53.         if(con != nullthrow new SQLException("已经开启了事务,不能重复开启!");  
  54.         con = ds.getConnection();//给con赋值,表示开启了事务  
  55.         con.setAutoCommit(false);//设置为手动提交  
  56.         tl.set(con);//把当前事务连接放到tl中  
  57.     }  
  58.       
  59.     /** 
  60.      * 提交事务 
  61.      * @throws SQLException  
  62.      */  
  63.     public static void commitTransaction() throws SQLException {  
  64.         Connection con = tl.get();//获取当前线程的事务连接  
  65.         if(con == nullthrow new SQLException("没有事务不能提交!");  
  66.         con.commit();//提交事务  
  67.         con.close();//关闭连接  
  68.         con = null;//表示事务结束!  
  69.         tl.remove();  
  70.     }  
  71.       
  72.     /** 
  73.      * 回滚事务 
  74.      * @throws SQLException  
  75.      */  
  76.     public static void rollbackTransaction() throws SQLException {  
  77.         Connection con = tl.get();//获取当前线程的事务连接  
  78.         if(con == nullthrow new SQLException("没有事务不能回滚!");  
  79.         con.rollback();  
  80.         con.close();  
  81.         con = null;  
  82.         tl.remove();  
  83.     }  
  84.       
  85.     /** 
  86.      * 释放Connection 
  87.      * @param con 
  88.      * @throws SQLException  
  89.      */  
  90.     public static void releaseConnection(Connection connection) throws SQLException {  
  91.         Connection con = tl.get();//获取当前线程的事务连接  
  92.         if(connection != con) {//如果参数连接,与当前事务连接不同,说明这个连接不是当前事务,可以关闭!  
  93.             if(connection != null &&!connection.isClosed()) {//如果参数连接没有关闭,关闭之!  
  94.                 connection.close();  
  95.             }  
  96.         }  
  97.     }  
  98. }  
  99. </span>  
package com.ppl.tools;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
 * 使用本类的方法,必须提供c3p0-copnfig.xml文件
 * @author pplsunny
 */
public class JdbcUtils {
	
	// 饿汉式
	private static DataSource ds = new ComboPooledDataSource();
	
	/**
	 * 它为null表示没有事务
	 * 它不为null表示有事务
	 * 当开启事务时,需要给它赋值
	 * 当结束事务时,需要给它赋值为null
	 * 并且在开启事务时,让dao的多个方法共享这个Connection
	 */
	private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
	
	public static DataSource getDataSource() {
		return ds;
	}
	
	/**
	 * dao使用本方法来获取连接
	 * @return
	 * @throws SQLException
	 */
	public static Connection getConnection() throws SQLException {
		/*
		 * 如果有事务,返回当前事务的con
		 * 如果没有事务,通过连接池返回新的con
		 */
		Connection con = tl.get();//获取当前线程的事务连接
		if(con != null) return con;
		return ds.getConnection();
	}
	
	/**
	 * 开启事务
	 * @throws SQLException 
	 */
	public static void beginTransaction() throws SQLException {
		Connection con = tl.get();//获取当前线程的事务连接
		if(con != null) throw new SQLException("已经开启了事务,不能重复开启!");
		con = ds.getConnection();//给con赋值,表示开启了事务
		con.setAutoCommit(false);//设置为手动提交
		tl.set(con);//把当前事务连接放到tl中
	}
	
	/**
	 * 提交事务
	 * @throws SQLException 
	 */
	public static void commitTransaction() throws SQLException {
		Connection con = tl.get();//获取当前线程的事务连接
		if(con == null) throw new SQLException("没有事务不能提交!");
		con.commit();//提交事务
		con.close();//关闭连接
		con = null;//表示事务结束!
		tl.remove();
	}
	
	/**
	 * 回滚事务
	 * @throws SQLException 
	 */
	public static void rollbackTransaction() throws SQLException {
		Connection con = tl.get();//获取当前线程的事务连接
		if(con == null) throw new SQLException("没有事务不能回滚!");
		con.rollback();
		con.close();
		con = null;
		tl.remove();
	}
	
	/**
	 * 释放Connection
	 * @param con
	 * @throws SQLException 
	 */
	public static void releaseConnection(Connection connection) throws SQLException {
		Connection con = tl.get();//获取当前线程的事务连接
		if(connection != con) {//如果参数连接,与当前事务连接不同,说明这个连接不是当前事务,可以关闭!
			if(connection != null &&!connection.isClosed()) {//如果参数连接没有关闭,关闭之!
				connection.close();
			}
		}
	}
}

三.一个详细的配置模板c3p0-config.xml

  1. <span style="font-size: 14px;"><c3p0-config>      
  2.     <default-config>      
  3.     <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->      
  4.     <property name="acquireIncrement">3</property>      
  5.         
  6.     <!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 -->      
  7.     <property name="acquireRetryAttempts">30</property>      
  8.         
  9.     <!--两次连接中间隔时间,单位毫秒。Default: 1000 -->      
  10.     <property name="acquireRetryDelay">1000</property>      
  11.         
  12.     <!--连接关闭时默认将所有未提交的操作回滚。Default: false -->      
  13.     <property name="autoCommitOnClose">false</property>      
  14.         
  15.     <!--c3p0将建一张名为Test的空表,并使用其自带的查询语句进行测试。如果定义了这个参数那么      
  16.     属性preferredTestQuery将被忽略。你不能在这张Test表上进行任何操作,它将只供c3p0测试      
  17.     使用。Default: null-->      
  18.     <property name="automaticTestTable">Test</property>      
  19.         
  20.     <!--获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效      
  21.     保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试      
  22.     获取连接失败后该数据源将申明已断开并永久关闭。Default: false-->      
  23.     <property name="breakAfterAcquireFailure">false</property>      
  24.         
  25.     <!--当连接池用完时客户端调用getConnection()后等待获取新连接的时间,超时后将抛出      
  26.     SQLException,如设为0则无限期等待。单位毫秒。Default: 0 -->      
  27.     <property name="checkoutTimeout">100</property>      
  28.         
  29.     <!--通过实现ConnectionTester或QueryConnectionTester的类来测试连接。类名需制定全路径。      
  30.     Default: com.mchange.v2.c3p0.impl.DefaultConnectionTester-->      
  31.     <property name="connectionTesterClassName"></property>      
  32.         
  33.     <!--指定c3p0 libraries的路径,如果(通常都是这样)在本地即可获得那么无需设置,默认null即可      
  34.     Default: null-->      
  35.     <property name="factoryClassLocation">null</property>      
  36.         
  37.     <!--Strongly disrecommended. Setting this to true may lead to subtle and bizarre bugs.      
  38.     (文档原文)作者强烈建议不使用的一个属性-->      
  39.     <property name="forceIgnoreUnresolvedTransactions">false</property>      
  40.         
  41.     <!--每60秒检查所有连接池中的空闲连接。Default: 0 -->      
  42.     <property name="idleConnectionTestPeriod">60</property>      
  43.         
  44.     <!--初始化时获取三个连接,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->      
  45.     <property name="initialPoolSize">3</property>      
  46.         
  47.     <!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->      
  48.     <property name="maxIdleTime">60</property>      
  49.         
  50.     <!--连接池中保留的最大连接数。Default: 15 -->      
  51.     <property name="maxPoolSize">15</property>      
  52.         
  53.     <!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements      
  54.     属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。      
  55.     如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0-->      
  56.     <property name="maxStatements">100</property>      
  57.         
  58.     <!--maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数。Default: 0 -->      
  59.     <property name="maxStatementsPerConnection"></property>      
  60.         
  61.     <!--c3p0是异步操作的,缓慢的JDBC操作通过帮助进程完成。扩展这些操作可以有效的提升性能      
  62.     通过多线程实现多个操作同时被执行。Default: 3-->      
  63.     <property name="numHelperThreads">3</property>      
  64.         
  65.     <!--当用户调用getConnection()时使root用户成为去获取连接的用户。主要用于连接池连接非c3p0      
  66.     的数据源时。Default: null-->      
  67.     <property name="overrideDefaultUser">root</property>      
  68.         
  69.     <!--与overrideDefaultUser参数对应使用的一个参数。Default: null-->      
  70.     <property name="overrideDefaultPassword">password</property>      
  71.         
  72.     <!--密码。Default: null-->      
  73.     <property name="password"></property>      
  74.         
  75.     <!--定义所有连接测试都执行的测试语句。在使用连接测试的情况下这个一显著提高测试速度。注意:      
  76.     测试的表必须在初始数据源的时候就存在。Default: null-->      
  77.     <property name="preferredTestQuery">select id from test where id=1</property>      
  78.         
  79.     <!--用户修改系统配置参数执行前最多等待300秒。Default: 300 -->      
  80.     <property name="propertyCycle">300</property>      
  81.         
  82.     <!--因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection提交的      
  83.     时候都将校验其有效性。建议使用idleConnectionTestPeriod或automaticTestTable      
  84.     等方法来提升连接测试的性能。Default: false -->      
  85.     <property name="testConnectionOnCheckout">false</property>      
  86.         
  87.     <!--如果设为true那么在取得连接的同时将校验连接的有效性。Default: false -->      
  88.     <property name="testConnectionOnCheckin">true</property>      
  89.         
  90.     <!--用户名。Default: null-->      
  91.     <property name="user">root</property>      
  92.         
  93.     <!--早期的c3p0版本对JDBC接口采用动态反射代理。在早期版本用途广泛的情况下这个参数      
  94.     允许用户恢复到动态反射代理以解决不稳定的故障。最新的非反射代理更快并且已经开始      
  95.     广泛的被使用,所以这个参数未必有用。现在原先的动态反射与新的非反射代理同时受到      
  96.     支持,但今后可能的版本可能不支持动态反射代理。Default: false-->      
  97.     <property name="usesTraditionalReflectiveProxies">false</property>    
  98.         
  99.     <property name="automaticTestTable">con_test</property>      
  100.     <property name="checkoutTimeout">30000</property>      
  101.     <property name="idleConnectionTestPeriod">30</property>      
  102.     <property name="initialPoolSize">10</property>      
  103.     <property name="maxIdleTime">30</property>      
  104.     <property name="maxPoolSize">25</property>      
  105.     <property name="minPoolSize">10</property>      
  106.     <property name="maxStatements">0</property>      
  107.     <user-overrides user="swaldman">      
  108.     </user-overrides>      
  109.     </default-config>      
  110.     <named-config name="dumbTestConfig">      
  111.     <property name="maxStatements">200</property>      
  112.     <user-overrides user="poop">      
  113.     <property name="maxStatements">300</property>      
  114.     </user-overrides>      
  115.     </named-config>      
  116.     </c3p0-config>   
  117. </span>  
<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>    
      
    <!--早期的c3p0版本对JDBC接口采用动态反射代理。在早期版本用途广泛的情况下这个参数    
    允许用户恢复到动态反射代理以解决不稳定的故障。最新的非反射代理更快并且已经开始    
    广泛的被使用,所以这个参数未必有用。现在原先的动态反射与新的非反射代理同时受到    
    支持,但今后可能的版本可能不支持动态反射代理。Default: false-->    
    <property name="usesTraditionalReflectiveProxies">false</property>  
      
    <property name="automaticTestTable">con_test</property>    
    <property name="checkoutTimeout">30000</property>    
    <property name="idleConnectionTestPeriod">30</property>    
    <property name="initialPoolSize">10</property>    
    <property name="maxIdleTime">30</property>    
    <property name="maxPoolSize">25</property>    
    <property name="minPoolSize">10</property>    
    <property name="maxStatements">0</property>    
    <user-overrides user="swaldman">    
    </user-overrides>    
    </default-config>    
    <named-config name="dumbTestConfig">    
    <property name="maxStatements">200</property>    
    <user-overrides user="poop">    
    <property name="maxStatements">300</property>    
    </user-overrides>    
    </named-config>    
    </c3p0-config> 

四.Tomcat中配置c3p0的方法:
1、server.xml中配置

  1. <span style="font-size: 14px;"><GlobalNamingResources>  
  2.     <!-- Editable user database that can also be used by  
  3.         UserDatabaseRealm to authenticate users  
  4.    -->  
  5.    <Resource  name="jdbc/test"  
  6.       auth="Container"  
  7.       description="User database that can be updated and saved"  
  8.       factory="org.apache.naming.factory.BeanFactory"  
  9.       driverClass="com.mysql.jdbc.Driver"  
  10.       maxPoolSize="4"  
  11.       minPoolSize="2"  
  12.       acquireIncrement="1"  
  13.       user="root"  
  14.       password=""  
  15.       type="com.mchange.v2.c3p0.ComboPooledDataSource"  
  16.       jdbcUrl="jdbc:mysql://localhost:3306/test"  
  17.     />  
  18. </GlobalNamingResources></span>  
<GlobalNamingResources>
    <!-- Editable user database that can also be used by
        UserDatabaseRealm to authenticate users
   -->
   <Resource  name="jdbc/test"
      auth="Container"
      description="User database that can be updated and saved"
      factory="org.apache.naming.factory.BeanFactory"
      driverClass="com.mysql.jdbc.Driver"
      maxPoolSize="4"
      minPoolSize="2"
      acquireIncrement="1"
      user="root"
      password=""
      type="com.mchange.v2.c3p0.ComboPooledDataSource"
      jdbcUrl="jdbc:mysql://localhost:3306/test"
    />
</GlobalNamingResources>

2、  conf目录下Context.xml

  1. <span style="font-size: 14px;"><ResourceLink name="jdbc/test" global="jdbc/test" type="javax.sql.DataSource"/></span>  
<ResourceLink name="jdbc/test" global="jdbc/test" type="javax.sql.DataSource"/>

3、  web.xml

  1. <span style="font-size: 14px;"><resource-ref>  
  2.     <res-ref-name>jdbc/ test</res-ref-name>  
  3.     <res-type>javax.sql.DataSource</res-type>  
  4.     <res-auth>Container</res-auth>  
  5. </resource-ref></span>  
<resource-ref>
	<res-ref-name>jdbc/ test</res-ref-name>
	<res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
</resource-ref>

JAVA测试代码:
  1. <span style="font-size: 14px;">InitialContext context = new InitialContext();  
  2. return (DataSource) context.lookup("java:comp/env/jdbc/test");  
  3. </span>  
InitialContext context = new InitialContext();
return (DataSource) context.lookup("java:comp/env/jdbc/test");

五.Hibernate中的配置

  1. <span style="font-size: 14px;"><?xml version='1.0' encoding='UTF-8'?>  
  2. <!DOCTYPE hibernate-configuration PUBLIC  
  3. "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
  4. "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
  5.   
  6. <!-- Generated by MyEclipse Hibernate Tools. -->  
  7. <hibernate-configuration>  
  8.   
  9.     <session-factory>  
  10.         <property name="c3p0.min_size">5</property>  
  11.         <property name="c3p0.max_size">100</property>  
  12.         <property name="c3p0.time_out">1800</property>  
  13.         <property name="c3p0.max_statement">100</property>  
  14.   
  15.         <property name="dialect">  
  16.         org.hibernate.dialect.MySQLDialect  
  17.         </property>  
  18.         <property name="jndi.url">  
  19.         jdbc:mysql://localhost:3306/noticemanager  
  20.         </property>  
  21.           
  22.         <!-- <property name="jndi.class">  
  23.         org.gjt.mm.mysql.Driver  
  24.         </property> -->  
  25.         <property name="connection.datasource">  
  26.         java:comp/env/jdbc/mysql1  
  27.         </property>  
  28.         <property name="connection.username">root</property>  
  29.         <property name="connection.password">xxxxxxxxx</property>  
  30.         <property name="hibernate.show_sql">true</property>  
  31.           
  32.         <!-- <property name="hibernate.use_outer_join">true</property> -->  
  33.         <mapping resource="com/dpoo/pojo/Notice.hbm.xml" />  
  34.   
  35.     </session-factory>  
  36.   
  37. </hibernate-configuration></span>  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值