A detailed description of spring's--C3P0 configuration

Source: Internet
Author: User
Tags valid xmlns

Reprint Please specify source: http://blog.csdn.net/l1028386804/article/details/51162560

Today, we will discuss in detail the C3P0 configuration problem in spring, well, without delaying everyone's time, we go directly to the topic, please see the following specific configuration file information:

<?xml version= "1.0" encoding= "UTF-8"?> <beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:x Si= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:jee= "Http://www.springframework.org/schema/jee" Xsi:schem alocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-2.0.xsd Http://www.springframework.org/schema/jee HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/JEE/SPR  
        Ing-jee-2.0.xsd "> <bean id=" dataSource "class=" Com.mchange.v2.c3p0.ComboPooledDataSource " destroy-method= "Close" > <property name= "Driverclass" > <value>com.mysql.jdbc.driver& lt;/value> </property> <property name= "Jdbcurl" > <value>jdbc:mysql:  
        192.168.3.110:3306/dbname?useunicode=true&characterencoding=gbk</value> </property> <property name= "User" > <value>root</value> </property> <property name= "password" > <value >root</value> </property> <!--the minimum number of connections that are kept in the connection pool. --<property name= "Minpoolsize" > <value>5</value> </property&gt  
   
 ; <!--The maximum number of connections that are kept in the connection pool. Default:15--<property name= "Maxpoolsize" > <value>30</value> &lt ;/property> <!--The number of connections obtained at initialization, the value should be between Minpoolsize and Maxpoolsize.  
        Default:3--<property name= "Initialpoolsize" > <value>10</value> </property> <!--maximum idle time, unused in 60 seconds, the connection is discarded. If 0, it will never be discarded. default:0--<property name= "MaxIdleTime" > <value>60</value> < /property> <!--When the connection in the connection pool is exhausted c3p0 the number of connections that are fetched at the same time. Default:3--<property name= "Acquireincrement" > <value>5</value> </property> <!--the standard parameters of JDBC to control the number of preparedstatements loaded within the data source. However, because the pre-cached statements belong to a single connection instead of the entire connection pool.  
  So setting this parameter takes into account a variety of factors. If both maxstatements and maxstatementsperconnection are 0, the cache is closed. default:0--> <property name= "maxstatements" > <value>0</value> < /property> <!--Check for idle connections in all connection pools every 60 seconds.  
        default:0--<property name= "Idleconnectiontestperiod" > <value>60</value> </property> <!--defines the number of repeated attempts to obtain a new connection from the database after a failure.  
        Default:30--<property name= "acquireretryattempts" > <value>30</value> </property> <!--getting a connection failure will cause any thread that waits for the connection pool to get the connection to throw an exception. However, the data source is still valid and continues to try to get the connection the next time you call Getconnection (). If set to True, the data source will declare broken and permanently shut down after attempting to acquire a connection failure. default:false--> <property name= "Breakafteracquirefailure" > <value>true</value&  
        Gt </pRoperty> <!--because of the high performance consumption, please use it only when you need it. If set to true then the validity of each connection submission is officer. We recommend using methods such as Idleconnectiontestperiod or automatictesttable to improve the performance of your connectivity tests. Default:false--<property name= "Testconnectiononcheckout" > <value>false</valu E> </property> </bean> <!--Hibernate Sessionfactory-<bean id= "ses Sionfactory "class=" Org.springframework.orm.hibernate3.LocalSessionFactoryBean "> <property name= "DataSource" > <ref local= "dataSource"/> </property> <property name= "M Appingresources "> <list> <value>com/xh/hibernate/vo/user.hbm.xml</value&  
            Gt </list> </property> <property name= "Hibernateproperties" > <props&gt  
                ; <prop key= "Hibernate.dialect" >org.hibernate.dialect.mysqldialect</prop> <prop key= "Hibernate.show_sql" >true</prop> <prop key= "hibernate.g Enerate_statistics ">true</prop> <prop key=" Hibernate.connection.release_mode "&GT;AUTO&LT;/PR  
        op> <prop key= "Hibernate.autoreconnect" >true</prop> </props>   </property> </bean> </beans>
Configuring spring Data Sources C3P0 and DBCP

Regardless of the persistence technology, the database must be accessed through a data connection, and in spring, the data connection is obtained through the data source. In previous applications, data sources are typically provided by Web application servers. In spring, you can not only get the application server's data source through Jndi, but you can also configure the data source directly in the spring container, and you can also create a data source in code that allows for non-dependent unit testing
Configure a data source
Spring contains two implementations of data sources in third-party dependency packages, one of which is Apache DBCP and the other is c3p0. You can use either of the two configuration data sources in the spring configuration file.
DBCP Data source
The DBCP class package is located in/LIB/JAKARTA-COMMONS/COMMONS-DBCP.JAR,DBCP is a database connection pool that relies on the Jakarta Commons-pool object pooling mechanism, so you must also include/lib/under the Classpath Jakarta-commons/commons-pool.jar. Here is a configuration fragment that uses DBCP to configure a MySQL data source:

XML code:

<bean id= "DataSource" class= "Org.apache.commons.dbcp.BasicDataSource"        
        destroy-method= "Close" >        
    < Property Name= "Driverclassname" value= "Com.mysql.jdbc.Driver"/>       
    <property name= "url" value= "jdbc:mysql:/ /localhost:3309/sampledb "/>       
    <property name=" username "value=" root "/>       
    <property name=" password "value=" 1234 "/>       
</bean>  
Basicdatasource provides the close () method to turn off the data source, so you must set the destroy-method= "close" property so that the data source shuts down gracefully when the spring container is closed. In addition to the data source properties that are required above, there are some common properties:
Defaultautocommit: Sets whether the connection returned from the data source takes the auto-commit mechanism, and the default value is true;
Defaultreadonly: Sets whether the data source can only perform read-only operations, the default value is false;
Maxactive: Maximum Connection database connection number, set to 0 o'clock, indicating no limit;
Maxidle: The maximum number of waiting connections, set to 0 o'clock, indicates no limit;
Maxwait: The maximum number of seconds to wait, in milliseconds, over time will be reported error message;
Validationquery: A query SQL statement that verifies that a connection is successful, the SQL statement must return at least one row of data, as you can simply set to: "SELECT COUNT (*) from user";
Removeabandoned: Whether self-interruption, default is false;
Removeabandonedtimeout: The data connection is automatically disconnected after a few seconds, and the value is provided when removeabandoned is true;
Logabandoned: If the interrupt event is logged, the default is false;
C3P0 Data source
C3P0 is an open source JDBC data source implementation project that is published in the Lib directory with Hibernate and implements the Connection and statement pools for JDBC3 and JDBC2 extension specification descriptions. The C3p0 class package is located in/lib/c3p0/c3p0-0.9.0.4.jar. Here is an Oracle data source configured using C3P0:

XML code

<bean id= "DataSource" class= "Com.mchange.v2.c3p0.ComboPooledDataSource"        
        destroy-method= "Close" >       
    <property name= "Driverclass" value= "Oracle.jdbc.driver.OracleDriver"/>       
    <property name= "Jdbcurl" value = "Jdbc:oracle:thin: @localhost: 1521:ora9i"/>       
    <property name= "user" value= "admin"/>       
    <property Name= "password" value= "1234"/>       
</bean>
Combopooleddatasource and Basicdatasource provide a close () method for shutting down the data source so that we can guarantee that the data source will be released successfully when the spring container is closed. C3P0 has richer configuration properties than DBCP, which allow for a variety of effective control over the data source:
Acquireincrement: When a connection in the connection pool is exhausted, C3P0 creates the number of new connections at once;
Acquireretryattempts: Defines the number of repeated attempts to obtain a new connection from the database after a failure, default is 30;
Acquireretrydelay: Two times the interval in the connection, in milliseconds, the default is 1000;
Autocommitonclose: All uncommitted operations are rolled back by default when the connection is closed. The default is false;
AUTOMATICTESTTABLE:C3P0 will build an empty table named Test and test it with its own query statement. If this parameter is defined, then the property preferredtestquery is ignored. You cannot take any action on this test table, it will be used in the C3P0 test, default is null;
Breakafteracquirefailure: Getting a connection failure will cause all threads waiting to get the connection to throw an exception. However, the data source is still valid and continues to try to get the connection the next time you call Getconnection (). If set to True, the data source will declare broken and permanently shut down after attempting to acquire a connection failure. The default is false;
Checkouttimeout: When the connection pool is exhausted, the client calls getconnection () to wait for a new connection, and then throws SqlException after the timeout, and waits indefinitely if set to 0. Unit milliseconds, default is 0;
Connectiontesterclassname: To test a connection by implementing a class of Connectiontester or Queryconnectiontester, the class name needs to be set to the fully qualified name. The default is Com.mchange.v2.C3P0.impl.DefaultConnectionTester;
Idleconnectiontestperiod: How many seconds to check the idle connection in all connection pools, the default is 0 means no check;
Initialpoolsize: The number of connections created at initialization should be taken between Minpoolsize and Maxpoolsize. The default is 3;
MaxIdleTime: Maximum idle time, the connection over idle time will be discarded. 0 or negative numbers will never be discarded. The default is 0;
Maxpoolsize: The maximum number of connections that are kept in the connection pool. The default is 15;
MAXSTATEMENTS:JDBC standard parameter to control the number of PreparedStatement loaded within the data source. However, because the pre-cached statement belong to a single connection instead of the entire connection pool. So setting this parameter takes many factors into account, and if both maxstatements and maxstatementsperconnection are 0, the cache is closed. The default is 0;
Maxstatementsperconnection: The maximum number of cache statement that a single connection in a connection pool has. The default is 0;
NUMHELPERTHREADS:C3P0 are asynchronous operations, and slow JDBC operations are done by helping the process. Extending these operations can effectively improve performance, and multiple operations are performed simultaneously through multithreading. The default is 3;
Preferredtestquery: Defines test statements that are executed by all connection tests. This parameter can significantly improve the test speed when using the connection test. The test table must exist at the time of the initial data source. default is null;
Propertycycle: The maximum number of seconds a user waits before modifying system configuration parameters. The default is 300;
Testconnectiononcheckout: Please use it only when you need it because of high performance consumption. If set to true then the validity of each connection submission is officer. It is recommended to use Idleconnectiontestperiod or automatictesttable
and other methods to improve the performance of the connection test. The default is false;
Testconnectiononcheckin: If set to true then the validity of the officer connection is obtained while the connection is made. The default is False.
Read the configuration file by referencing the properties:
<bean id= "Propertyconfigurer"      
        class= " Org.springframework.beans.factory.config.PropertyPlaceholderConfigurer ">       
    <property name=" Location " Value= "/web-inf/jdbc.properties"/>       
</bean>       
<bean id= "DataSource" class= " Org.apache.commons.dbcp.BasicDataSource "        
        destroy-method=" Close ">       
    <property name=" Driverclassname " Value= "${jdbc.driverclassname}"/>       
    <property name= "url" value= "${jdbc.url}"/>       
    <property name= " Username "value=" ${jdbc.username} "/>       
    <property name=" password "value=" ${jdbc.password} "/>       
</ Bean>    
To define a property value in the Jdbc.properties property file:

Jdbc.driverclassname= com.mysql.jdbc.Driver 
jdbc.url= jdbc:mysql://localhost:3309/sampledb 
Jdbc.username=root 

Tip developers often accidentally type some spaces before and after the ${xxx}, and the space characters are merged with the variable as the value of the property. Such as: The property configuration item, before and after the space, after being parsed, the value of username is "1234", which will cause the final error, so you need special care.

Get Jndi Data source

If the application is configured on a high-performance application server, such as WebLogic or WebSphere, we may prefer to use the data source provided by the application server itself. The data source for the application server is used by Jndi open callers, and spring specifically provides the Jndiobjectfactorybean class that references the Jndi resource. The following is a simple configuration: XML code

<bean id= "DataSource" class= "Org.springframework.jndi.JndiObjectFactoryBean" >       
    <property name= " Jndiname "value=" JAVA:COMP/ENV/JDBC/BBT "/>       
</bean>

Specifies the referenced Jndi data source name by Jndiname.

SPRING2.0 provides a JEE namespace for acquiring the Java EE resource, which, through the Jee namespace, can effectively simplify the reference to the Java EE resource. The following is a configuration that uses the Jee namespace to reference a Jndi data source:

XML code

<beans Xmlns=http://www.springframework.org/schema/beans     
xmlns:xsi=http://www.w3.org/2001/ Xmlschema-instance     
Xmlns:jee=http://www.springframework.org/schema/jee     
xsi:schemalocation= "/http Www.springframework.org/schema/beans      
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd      
Http://www.springframework.org/schema/jee     
http://www.springframework.org/schema/jee/spring-jee-2.0.xsd " >       
   <jee:jndi-lookup id= "DataSource" jndi-name= "JAVA:COMP/ENV/JDBC/BBT"/>       
</beans>   
Spring's data source implementation class
Spring itself also provides a simple data source implementation class Drivermanagerdatasource, which is located in the Org.springframework.jdbc.datasource package. This class implements the Javax.sql.DataSource interface, but it does not provide a mechanism for pooling connections, and it simply creates a new connection each time a call to getconnection () gets a new connection. Therefore, this data source class is better suited for use in unit testing or simple standalone applications because it does not require additional dependency classes.
Now, let's take a look at the simple use of Drivermanagerdatasource: Of course, we can also use the Drivermanagerdatasource directly in a configuration way.
Java code
Drivermanagerdatasource ds = new Drivermanagerdatasource ();       
Ds.setdriverclassname ("Com.mysql.jdbc.Driver");       
Ds.seturl ("Jdbc:mysql://localhost:3309/sampledb");       
Ds.setusername ("root");       
Ds.setpassword ("1234");       
Summary
Regardless of which persistence technology is used, you need to define a data source. Spring comes with an implementation class package of two data sources that you can choose to define yourself. In the actual deployment, we may be directly using the data source provided by the application server itself, at which point the data source in Jndi can be referenced through the Jndiobjectfactorybean or Jee namespace.
The difference between DBCP and C3PO configuration:
C3PO:DBCP:
XML code

<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:@10.10.10.6:1521:d atabasename</value>   
     </property>   
    <property name= "user" >   
        <value>testAdmin< /value>   
    </property>   
    <property name= "password" >   
        <value>123456</value>   
    </property>   
XML code

<bean id= "DataSource" class= "Org.apache.commons.dbcp.BasicDataSource" destroy-method= "Close" >   
    < Property name= "Driverclassname" >   
        <value>oracle.jdbc.driver.OracleDriver</value>   
    </ property>   
    <property name= "url" >              
        <value>jdbc:oracle:thin:@10.10.10.6:1521:databasename </value>   
     </property>   
    <property name= "username" >   
        <value>testadmin</value >   
    </property>   
    <property name= "password" >   
        <value>123456</value>   
    </property>   
</bean> 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.