Java Siege Lion Road-Review JDBC (database connection pool: C3P0, DBCP)

Source: Internet
Author: User
Tags connection pooling

Review database Connection pool: C3P0, DBCP

1, the advantages of database connection pooling technology:

• Resource reuse:Due to the reuse of database connections, there is a high performance overhead associated with frequent creation and release of connections. On the basis of reducing the system consumption, on the other hand, it also increases the stability of the system operating environment.• Faster system response Speed:Database connection pooling during initialization, several database connections are often created to be placed in the connection pool for backup. The initialization of the connection is now complete. For business request processing, direct utilization of existing available connections avoids the time overhead of database connection initialization and release, thus reducing system response time.• New means of resource allocation:For multiple applications sharing the same database system, the application layer can be configured through the database connection pool, the application of a maximum number of available database connections limit, to avoid an application exclusive all database resources.• Unified connection Management to avoid database connection leaks:In a more complete database connection pool implementation, it is possible to forcibly reclaim the occupied connection based on the pre-occupancy timeout setting, thus avoiding the potential resource leaks in regular database connection operations. 1) Two open source database connection pools:The JDBC database connection pool is represented by Javax.sql.DataSource, DataSource is just an interface that is typically implemented by the server (Weblogic, WebSphere, Tomcat), and some open source organizations provide the implementation: –DBCP database Connection pool–c3p0 database Connection poolDataSource is often referred to as a data source, which contains two parts of connection pooling and connection pooling management, and it is customary to often call DataSource a connection pool a:dbcp Data Source:DBCP is an open source connection pool implementation under the Apache Software Foundation, which relies on another open source system under the organization: Common-pool. To use this connection pool implementation, add the following two jar files to the system: – Commons-dbcp.jar: The implementation of the connection pool. – Commons-pool.jar: A dependency library for connection pooling implementations. •The connection pool for Tomcat is implemented with this connection pool。 The database connection pool can be used either in combination with the application server or independently by the application.DBCP Data Source Usage Example:• Unlike data sources and database connections, there is no need to create multiple data sources, which are factories that generate database connections, so the entire application needs only one data source. • When the database access is complete, the program closes the database connection as before: Conn.close (); But the code above does not close the physical connection to the database, it simply frees the database connection and returns it to the database connection pool.
    /*** 1. Load DBCP's properties profile: The keys in the configuration file require attributes from Basicdatasource *. * 2. Call Basicdatasourcefactory's CreateDataSource method to create the DataSource * instance * 3.      Gets the database connection from the DataSource instance. */@Test Public voidTestdbcpwithdatasourcefactory ()throwsexception{Properties Properties=NewProperties (); InputStream instream= Jdbctest.class. getClassLoader (). getResourceAsStream ("Dbcp.properties");                Properties.load (instream); DataSource DataSource=Basicdatasourcefactory.createdatasource (properties);         System.out.println (Datasource.getconnection ()); //Basicdatasource Basicdatasource =//(Basicdatasource) DataSource;//        //System.out.println (basicdatasource.getmaxwait ());    }        /*** Use DBCP database connection pool * 1. Add a jar package (2 jar packages). Dependent on Commons pool * 2. Create a database connection pool * 3. Specify the Required property * 4 for the data source instance. Get a database connection from the data source *@throwsSQLException*/@Test Public voidTESTDBCP ()throwssqlexception{FinalBasicdatasource DataSource =NewBasicdatasource (); //2. Specify the required properties for the data source instanceDatasource.setusername ("root"); Datasource.setpassword ("1230"); Datasource.seturl ("Jdbc:mysql:///atguigu"); Datasource.setdriverclassname ("Com.mysql.jdbc.Driver"); //3. Specify some optional properties for the data source. //1). Specify the number of initialized connections in the database connection poolDatasource.setinitialsize (5); //2). Specify the maximum number of connections: the number of connections that can be requested simultaneously to the database at the same timeDatasource.setmaxactive (5); //3). Specify the number of small connections: the minimum number of idle connections saved in the database connection poolDatasource.setminidle (2); //4). The maximum time to wait for the database connection pool to allocate connections. The unit is in milliseconds. An exception will be thrown beyond that time. Datasource.setmaxwait (1000 * 5); //4. Get the database connection from the data sourceConnection Connection =datasource.getconnection ();                 System.out.println (Connection.getclass ()); Connection=datasource.getconnection ();                 System.out.println (Connection.getclass ()); Connection=datasource.getconnection ();                 System.out.println (Connection.getclass ()); Connection=datasource.getconnection ();                 System.out.println (Connection.getclass ()); Connection Connection2=datasource.getconnection (); System.out.println (">" +Connection2.getclass ()); NewThread () { Public voidrun () {Connection conn; Try{conn=datasource.getconnection ();                 System.out.println (Conn.getclass ()); } Catch(SQLException e) {e.printstacktrace ();        }            };                }.start (); Try{Thread.Sleep (5500); } Catch(interruptedexception e) {e.printstacktrace ();    } connection2.close (); }
DBCP Data Source Example
Username=rootpassword=1230driverclassname=com.mysql.jdbc.Driverurl=jdbc:mysql:/ //atguiguinitialsize=10maxactive=50minidle =5maxwait =5000
dbcp.properties

B:C3P0 Data source

    /*** 1. Create a C3p0-config.xml file, * Refer to the contents of appendix B:configuation files in the Help document * 2. Create Combopooleddatasource       Example: * DataSource DataSource = * New Combopooleddatasource ("helloc3p0"); * 3.      Gets the database connection from the DataSource instance. */@Test Public voidTestc3powithconfigfile ()throwsexception{DataSource DataSource=NewCombopooleddatasource ("Helloc3p0");                 System.out.println (Datasource.getconnection ()); Combopooleddatasource Combopooleddatasource=(Combopooleddatasource) DataSource;     System.out.println (Combopooleddatasource.getmaxstatements ()); } @Test Public voidTESTC3P0 ()throwsexception{Combopooleddatasource CPDs=NewCombopooleddatasource (); Cpds.setdriverclass ("Com.mysql.jdbc.Driver");//loads the JDBC driverCpds.setjdbcurl ("Jdbc:mysql:///atguigu" ); Cpds.setuser ("Root"); Cpds.setpassword ("1230");     System.out.println (Cpds.getconnection ()); }
c3p0 Data Source Example
<?xml version= "1.0" encoding= "UTF-8"?><c3p0-config> <named-config name= "helloc3p0" > &L t;! --Specify the basic properties of the connection data source--<property name= "user" >root</property> <property name= "password" >123 0</property> <property name= "Driverclass" >com.mysql.jdbc.Driver</property> <property na Me= "Jdbcurl" >jdbc:mysql:///atguigu</property><!--If the number of connections in the database is insufficient, how many connections to the database server at a time (<property name= "Acquireincrement" >5</property> < !--the number of connections when the database connection pool is initialized--<property name= "Initialpoolsize" >5</property> <!--the smallest database connection in the database connections pool Number of connections--<property name= "Minpoolsize" >5</property> <!--the largest database connection in the database connection pool--< Property Name= "Maxpoolsize" >10</property> <!--c3p0 the number of Statement the database connection pool can maintain--<propert Y name= "maxstatements" >20</property> <!--the number of Statement objects that can be used per connection--<property name= " Maxstatementsperconnection ">5</property> </named-config> </c3p0-config>
C3p0-config.xml

(To be Continued ...) )

Java Siege Lion Road-Review JDBC (database connection pool: C3P0, DBCP)

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.