c3p0在spring的配置(详解)

C3P0是一个开放源代码的JDBC连接池,它在lib目录中与Hibernate一起发布,包括了实现jdbc3和 jdbc2扩展规范说明的Connection 和Statement 池的DataSources 对象。
  <!--当连接池中的连接耗尽的时候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>
  ###########################
  ### C3P0 Connection Pool###
  ###########################
  #hibernate.c3p0.max_size 2
  #hibernate.c3p0.min_size 2
  #hibernate.c3p0.timeout 5000
  #hibernate.c3p0.max_statements 100
  #hibernate.c3p0.idle_test_period 3000
  #hibernate.c3p0.acquire_increment 2
  #hibernate.c3p0.validate false
  在hibernate.cfg.xml文件里面加入如下的配置:
  <!-- 最大连接数 -->
   <property name="hibernate.c3p0.max_size">20</property>
  <!-- 最小连接数 -->
  <property name="hibernate.c3p0.min_size">5</property>
  <!-- 获得连接的超时时间,如果超过这个时间,会抛出异常,单位毫秒 -->
  <property name="hibernate.c3p0.timeout">120</property>
  <!-- 最大的PreparedStatement的数量 -->
  <property name="hibernate.c3p0.max_statements">100</property>
  <!-- 每隔120秒检查连接池里的空闲连接 ,单位是秒-->
  <property name="hibernate.c3p0.idle_test_period">120</property>
  <!-- 当连接池里面的连接用完的时候,C3P0一下获取的新的连接数 -->
  <property name="hibernate.c3p0.acquire_increment">2</property>
  <!-- 每次都验证连接是否可用 -->

  <property name="hibernate.c3p0.validate">true</property>


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

C3P0是一个开源的JDBC连接池。

在Spring中,C3P0的一些配置,介绍如下(只列了一部分,不是全部)

  1. <!-- c3p0连接池配置 -->  
  2.      <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">  
  3.           <!-- 用户名-->  
  4.           <property name="user" value="${username}"/>  
  5.           <!-- 用户密码-->  
  6.           <property name="password" value="${password}"/>  
  7.           <property name="driverClass" value="${driver_class}"/>  
  8.           <property name="jdbcUrl" value="${url}"/>  
  9.   
  10.            <!--连接池中保留的最大连接数。默认值: 15 -->   
  11.           <property name="maxPoolSize" value="20"/>  
  12.           <!-- 连接池中保留的最小连接数,默认为:3-->  
  13.           <property name="minPoolSize" value="2"/>  
  14.           <!-- 初始化连接池中的连接数,取值应在minPoolSize与maxPoolSize之间,默认为3-->  
  15.           <property name="initialPoolSize" value="2"/>  
  16.   
  17.           <!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。默认值: 0 -->   
  18.           <property name="maxIdleTime">60</property>  
  19.             
  20.           <!-- 当连接池连接耗尽时,客户端调用getConnection()后等待获取新连接的时间,超时后将抛出SQLException,如设为0则无限期等待。单位毫秒。默认: 0 -->   
  21.           <property name="checkoutTimeout" value="3000"/>  
  22.             
  23.           <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。默认值: 3 -->   
  24.           <property name="acquireIncrement" value="2"/>  
  25.   
  26.          <!--定义在从数据库获取新连接失败后重复尝试的次数。默认值: 30 ;小于等于0表示无限次-->   
  27.           <property name="acquireRetryAttempts" value="0"/>  
  28.   
  29.           <!--重新尝试的时间间隔,默认为:1000毫秒-->   
  30.           <property name="acquireRetryDelay" value="1000" />  
  31.   
  32.           <!--关闭连接时,是否提交未提交的事务,默认为false,即关闭连接,回滚未提交的事务 -->   
  33.           <property name="autoCommitOnClose">false</property>  
  34.   
  35.           <!--c3p0将建一张名为Test的空表,并使用其自带的查询语句进行测试。如果定义了这个参数那么属性preferredTestQuery将被忽略。你不能在这张Test表上进行任何操作,它将只供c3p0测试使用。默认值: null -->   
  36.           <property name="automaticTestTable">Test</property>  
  37.   
  38.           <!--如果为false,则获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常,但是数据源仍有效保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试获取连接失败后该数据源将申明已断开并永久关闭。默认: false-->   
  39.           <property name="breakAfterAcquireFailure">false</property>  
  40.   
  41.           <!--每60秒检查所有连接池中的空闲连接。默认值: 0,不检查 -->   
  42.           <property name="idleConnectionTestPeriod">60</property>  
  43.           <!--c3p0全局的PreparedStatements缓存的大小。如果maxStatements与maxStatementsPerConnection均为0,则缓存不生效,只要有一个不为0,则语句的缓存就能生效。如果默认值: 0-->   
  44.           <property name="maxStatements">100</property>  
  45.           <!--maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数。默认值: 0 -->   
  46.           <property name="maxStatementsPerConnection"></property>  
  47.      </bean>  

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

C3P0更详细的配置项及其含义,请参考:http://www.mchange.com/projects/c3p0/index.html,部分内容摘录如下:

acquireIncrement
acquireRetryAttempts
acquireRetryDelay
autoCommitOnClose
automaticTestTable
breakAfterAcquireFailure
checkoutTimeout
connectionCustomizerClassName
connectionTesterClassName
debugUnreturnedConnectionStackTraces
factoryClassLocation
forceIgnoreUnresolvedTransactions
idleConnectionTestPeriod
initialPoolSize
maxAdministrativeTaskTime
maxConnectionAge
maxIdleTime
maxIdleTimeExcessConnections
maxPoolSize
maxStatements
maxStatementsPerConnection
minPoolSize
numHelperThreads
overrideDefaultUser
overrideDefaultPassword
password
preferredTestQuery
propertyCycle
testConnectionOnCheckin
testConnectionOnCheckout
unreturnedConnectionTimeout
user
usesTraditionalReflectiveProxies
acquireIncrement
Default: 3
acquireRetryAttempts
Default: 30
acquireRetryDelay
Default: 1000
autoCommitOnClose
Default: false
automaticTestTable
Default: null
breakAfterAcquireFailure
Default: false
checkoutTimeout
Default: 0
The number of milliseconds a client calling getConnection() will wait for a Connection to be checked-in or acquired when the pool is exhausted. Zero means wait indefinitely. Setting any positive value will cause the getConnection() call to time-out and break with an  SQLException after the specified number of milliseconds.
connectionCustomizerClassName
Default: null
The fully qualified class-name of an implememtation of the  ConnectionCustomizer interface, which users can implement to set up Connections when they are acquired from the database, or on check-out, and potentially to clean things up on check-in and Connection destruction. If standard Connection properties (holdability, readOnly, or transactionIsolation) are set in the ConnectionCustomizer's onAcquire() method, these will override the Connection default values.
connectionTesterClassName
Default: com.mchange.v2.c3p0.impl.DefaultConnectionTester
The fully qualified class-name of an implememtation of the  ConnectionTester interface, or  QueryConnectionTester if you would like instances to have access to a user-configured  preferredTestQuery. This can be used to customize how c3p0 DataSources test Connections, but with the introduction of  automaticTestTable and  preferredTestQuery configuration parameters, "rolling your own" should be overkill for most users. [See  "Configuring Connection Testing"]
debugUnreturnedConnectionStackTraces
Default: false
If true, and if  unreturnedConnectionTimeout is set to a positive value, then the pool will capture the stack trace (via an Exception) of all Connection checkouts, and the stack traces will be printed when unreturned checked-out Connections timeout. This is intended to debug applications with Connection leaks, that is applications that occasionally fail to return Connections, leading to pool growth, and eventually exhaustion (when the pool hits  maxPoolSize with all Connections checked-out and lost). This parameter should only be set while debugging, as capturing the stack trace will slow down every Connection check-out.
Does Not Support Per-User Overrides.
factoryClassLocation
Default: null
DataSources that will be bound by JNDI and use that API's Referenceable interface to store themselves may specify a URL from which the class capable of dereferencing a them may be loaded. If (as is usually the case) the c3p0 libraries will be locally available to the JNDI service, leave this set as null.
Does Not Support Per-User Overrides.
forceIgnoreUnresolvedTransactions
Default: false
idleConnectionTestPeriod
Default: 0
initialPoolSize
Default: 3
maxAdministrativeTaskTime
Default: 0
Seconds before c3p0's thread pool will try to interrupt an apparently hung task. Rarely useful. Many of c3p0's functions are not performed by client threads, but asynchronously by an internal thread pool. c3p0's asynchrony enhances client performance directly, and minimizes the length of time that critical locks are held by ensuring that slow jdbc operations are performed in non-lock-holding threads. If, however, some of these tasks "hang", that is they neither succeed nor fail with an Exception for a prolonged period of time, c3p0's thread pool can become exhausted and administrative tasks backed up. If the tasks are simply slow, the best way to resolve the problem is to increase the number of threads, via  numHelperThreads. But if tasks sometimes hang indefinitely, you can use this parameter to force a call to the task thread's  interrupt() method if a task exceeds a set time limit. [c3p0 will eventually recover from hung tasks anyway by signalling an "APPARENT DEADLOCK" (you'll see it as a warning in the logs), replacing the thread pool task threads, and interrupt()ing the original threads. But letting the pool go into APPARENT DEADLOCK and then recover means that for some periods, c3p0's performance will be impaired. So if you're seeing these messages, increasing  numHelperThreads and setting  maxAdministrativeTaskTime might help. maxAdministrativeTaskTime should be large enough that any resonable attempt to acquire a Connection from the database, to test a Connection, or two destroy a Connection, would be expected to succeed or fail within the time set. Zero (the default) means tasks are never interrupted, which is the best and safest policy under most circumstances. If tasks are just slow, allocate more threads. If tasks are hanging forever, try to figure out why, and maybe setting  maxAdministrativeTaskTime can help in the meantime.
Does Not Support Per-User Overrides.
maxConnectionAge
Default: 0
Seconds, effectively a time to live. A Connection older than  maxConnectionAge will be destroyed and purged from the pool. This differs from  maxIdleTime in that it refers to absolute age. Even a Connection which has not been much idle will be purged from the pool if it exceeds  maxConnectionAge. Zero means no maximum absolute age is enforced.
maxIdleTime
Default: 0
maxIdleTimeExcessConnections
Default: 0
Number of seconds that Connections in excess of  minPoolSize should be permitted to remain idle in the pool before being culled. Intended for applications that wish to aggressively minimize the number of open Connections, shrinking the pool back towards minPoolSize if, following a spike, the load level diminishes and Connections acquired are no longer needed. If  maxIdleTime is set, maxIdleTimeExcessConnections should be smaller if the parameter is to have any effect. Zero means no enforcement, excess Connections are not idled out.
maxPoolSize
Default: 15
maxStatements
Default: 0
maxStatementsPerConnection
Default: 0
minPoolSize
Default: 3
numHelperThreads
Default: 3
c3p0 is very asynchronous. Slow JDBC operations are generally performed by helper threads that don't hold contended locks. Spreading these operations over multiple threads can significantly improve performance by allowing multiple operations to be performed simultaneously.
Does Not Support Per-User Overrides.
overrideDefaultUser
Default: null
Does Not Support Per-User Overrides.
overrideDefaultPassword
Default: null
Does Not Support Per-User Overrides.
password
Default: null
Does Not Support Per-User Overrides.
preferredTestQuery
Default: null
Defines the query that will be executed for all connection tests, if the default ConnectionTester (or some other implementation of  QueryConnectionTester, or better yet  FullQueryConnectionTester) is being used. Defining a  preferredTestQuery that will execute quickly in your database may dramatically speed up Connection tests. (If no  preferredTestQuery is set, the default ConnectionTester executes a  getTables() call on the Connection's DatabaseMetaData. Depending on your database, this may execute more slowly than a "normal" database query.)  NOTE: The table against which your preferredTestQuery will be run must exist in the database schema prior to your initialization of your DataSource. If your application defines its own schema, tryautomaticTestTable instead. [See  "Configuring Connection Testing"]
propertyCycle
Default: 0
testConnectionOnCheckin
Default: false
testConnectionOnCheckout
Default: false
unreturnedConnectionTimeout
Default: 0
Seconds. If set, if an application checks out but then fails to check-in [i.e. close()] a Connection within the specified period of time, the pool will unceremoniously destroy() the Connection. This permits applications with occasional Connection leaks to survive, rather than eventually exhausting the Connection pool. And that's a shame. Zero means no timeout, applications are expected to close() their own Connections. Obviously, if a non-zero value is set, it should be to a value longer than any Connection should reasonably be checked-out. Otherwise, the pool will occasionally kill Connections in active use, which is bad.  This is basically a bad idea, but it's a commonly requested feature. Fix your $%!@% applications so they don't leak Connections! Use this temporarily in combination with debugUnreturnedConnectionStackTraces to figure out where Connections are being checked-out that don't make it back into the pool!
user
Default: null
Does Not Support Per-User Overrides.
usesTraditionalReflectiveProxies
Default: false
c3p0 originally used reflective dynamic proxies for implementations of Connections and other JDBC interfaces. As of c3p0-0.8.5, non-reflective, code-generated implementations are used instead. As this was a major change, and the old codebase had been extensively used and tested, this parameter was added to allow users to revert of they had problems. The new, non-reflexive implementation is faster, and has now been widely deployed and tested, so it is unlikely that this parameter will be useful. Both the old reflective and newer non-reflective codebases are being maintained, but support for the older codebase may (or may not) be dropped in the future.
=======================================================================================================================

一个task应用数据库连接配置的例子:

  1. <bean id="dataSource" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">   
  2.           <property name="staticMethod">  
  3.               <value>com.mchange.v2.c3p0.DataSources.pooledDataSource</value>  
  4.           </property>  
  5.           <property name="arguments">  
  6.               <list>  
  7.                 <ref local="olpsUnpooledDataSource"/>  
  8.                     <props>  
  9.                         <prop key="acquireIncrement">1</prop>  
  10.                         <prop key="initialPoolSize">1</prop>  
  11.                         <prop key="minPoolSize">1</prop>  
  12.                         <prop key="maxPoolSize">5</prop>  
  13.                         <prop key="maxIdleTime">1800</prop>  
  14.                         <prop key="maxIdleTimeExcessConnections">1000</prop> <!-- 自动收缩连接用的,单位秒-->  
  15.                         <!-- 自动重连需要的三个参数  -->  
  16.                         <prop key="acquireRetryAttempts">30</prop>  
  17.                         <prop key="acquireRetryDelay">1000</prop>  
  18.                         <prop key="breakAfterAcquireFailure">false</prop>  
  19.                         <!-- 获取一个connection需要的时间,单位毫秒 -->  
  20.                         <prop key="checkoutTimeout">500</prop>  
  21.                     </props>  
  22.             </list>  
  23.         </property>  
  24.     </bean>  
  25.          
  26.     <bean id="olpsUnpooledDataSource" class="com.mchange.v2.c3p0.DriverManagerDataSource">   
  27.         <property name="driverClass">  
  28.             <value>com.alibaba.china.jdbc.SimpleDriver</value>  
  29.         </property>  
  30.         <property name="jdbcUrl">  
  31.             <value>${database.driver.url}</value>  
  32.         </property>  
  33.         <property name="properties">  
  34.             <bean class="com.alibaba.china.biz.common.security.SecureIdentityLoginModule">  
  35.                 <property name="user"><value>${username}</value></property>  
  36.                 <property name="password"><value>${password}</value></property>  
  37.                 <property name="bigStringTryClob"><value>true</value></property>  
  38.                 <property name="clientEncoding"><value>GBK</value></property>  
  39.                 <property name="serverEncoding"><value>ISO-8859-1</value></property>  
  40.             </bean>  
  41.         </property>  
  42.     </bean> 

例子如下:

<bean id="dataSource_1"    class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <property name="driverClass" value="${jdbc.driver}" />
        <property name="jdbcUrl" value="${jdbc.url}" />
        <property name="user" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="initialPoolSize" value="5"/>
        <property name="minPoolSize" value="10"/>
        <property name="maxPoolSize" value="20"/>
        <property name="maxIdleTime" value="1200"/>
        <property name="acquireIncrement" value="5"/>
        <property name="idleConnectionTestPeriod" value="60"/>
        <property name="unreturnedConnectionTimeout" value="1260" />  
        <property name="debugUnreturnedConnectionStackTraces" value="false" />
        <property name="numHelperThreads" value="5" />  
    </bean>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值