Database Connection Pool

Source: Internet
Author: User

1. Customizing the database connection pool
 Public classMypool {Private intInit_count = 3; Private intMax_count = 6; Private intCurr_count = 0; PrivateLinkedlist<connection> pool =NewLinkedlist<connection>();  PublicMypool () { for(inti = 0; i < Init_count; i++) {Curr_count++;        Pool.addlast (CreateConnection ()); }    }    /*** Using the proxy class, each time the connection Close method is called, the connection is placed in the connection pool*/    PrivateConnection createconnection () {Try{class.forname ("Com.mysql.jdbc.Driver"); Connection Connection= Drivermanager.getconnection ("Jdbc:mysql:///test", "root", "juaner767"); Connection Proxy=(Connection) proxy.newproxyinstance (Connection.getclass (). getClassLoader (),//class Loader//Connection.getclass (). Getinterfaces () implements an interface that is used when the object is a concrete class                    NewClass[]{connection.class},//connection is an interface, so use it like this                    NewInvocationhandler () {//the transaction handler is automatically triggered when the connection object method is called@Override PublicObject Invoke (Object proxy, Method method, object[] args)throwsthrowable {String name=Method.getname (); Object result=NULL; //when the Close method is executed, the connection is placed in the connection pool                            if("Close". Equals (name)) {System.out.println ("Call object Monitored interface");                            Releaseconnection (connection); }Else{result=Method.invoke (connection, args); }                            returnresult;            }                    }            ); returnproxy; } Catch(Exception e) {Throw NewRuntimeException (e); }    }     PublicConnection getconnection () {Connection Connection=NULL; if(Pool.size () > 0) {Connection=Pool.removefirst (); }Else{            if(Curr_count <max_count) {Curr_count++; Connection=createconnection (); }Else {                Throw NewRuntimeException ("The maximum number of connections is currently reached, unable to get the connection!")); }        }        returnconnection; }     Public voidreleaseconnection (Connection Connection) {if(Connection = =NULL)            return; if(Pool.size () <init_count) Pool.addlast (connection); Else{            Try{connection.close (); } Catch(SQLException e) {Throw NewRuntimeException (e); } Curr_count--; }    }}
2.DBCP Connection Pool Components

DBCP is an open source connection pool implementation under the Apache Software Foundation. Using a DBCP data source, the application should add the following two jar files to the system:
Commons-dbcp.jar: Implementation of connection pooling
Commons-pool.jar: Dependency libraries 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.

Db.properties:

Url=jdbc:mysql:///studentdriverclassname=com.mysql.jdbc.driverusername=rootpassword=juaner767initialsize= 3maxactive=6maxidle=3000

To use the DBCP connection pool:

@Test Public voidTest2 ()throwsException {//Load configuration fileProperties prop =NewProperties (); InputStream in= Demo1.class. getResourceAsStream ("Db.properties"); Prop.load (in);
DataSource DataSource=Basicdatasourcefactory.createdatasource (prop); Connection Connection=datasource.getconnection (); Connection.preparestatement ("DELETE from student_info WHERE stuid = 2008006"). Executeupdate (); Connection.close (); }

3.C3P0 Connection Pool Components

C3P0 is an open source JDBC connection pool that implements the data source and Jndi bindings, and supports the standard extensions of the JDBC3 specification and JDBC2. The open source projects that currently use it are hibernate,spring and so on.

Set configuration file C3p0-config.xml under src:

<C3p0-config>  <Default-config>     < Propertyname= "Jdbcurl">Jdbc:mysql://localhost:3306/student</ Property>     < Propertyname= "Driverclass">Com.mysql.jdbc.Driver</ Property>     < Propertyname= "User">Root</ Property>     < Propertyname= "Password">juaner767</ Property>     < Propertyname= "Initialpoolsize">3</ Property>     < Propertyname= "Maxpoolsize">6</ Property>     < Propertyname= "MaxIdleTime">1000</ Property>  </Default-config></C3p0-config>

To use the C3P0 connection pool:

    @Test public    void Test2 () throws exception{        //auto-load configuration file for c3p0 under SRC c3p0-config.xml        Combopooleddatasource DataSource = new Combopooleddatasource ();        Connection Connection = Datasource.getconnection ();        PreparedStatement PreparedStatement  = null;        String sql = "INSERT into Student_info (stuname,telephone) VALUES (?,?) ";        PreparedStatement = connection.preparestatement (sql);        for (int i = 0;i<i++) {            preparedstatement.setstring (1, "Test" +i);            Preparedstatement.setint (2,1353356234);            Preparedstatement.executeupdate ();        }        Connection.close ();    }
4. The difference dbcp does not automatically reclaim the function of idle connections. The C3P0 has auto-recycle idle connection function. 5. Using the C3P0 connection pool in Hibernate

Configure in Hibernate.cfg.xml:

        <!--Connection Pool Configuration -        <!--Connection Pool Management class, driver management class -        < Propertyname= "Hibernate.connection.provider_class">Org.hibernate.connection.C3P0ConnectionProvider</ Property>        <!--Configuring connection pool parameter information -        < Propertyname= "Hibernate.c3p0.min_size">2</ Property>        < Propertyname= "Hibernate.c3p0.max_size">4</ Property>        < Propertyname= "Hibernate.c3p0.timeout">5000</ Property>        < Propertyname= "Hibernate.c3p0.max_statements">10</ Property>        < Propertyname= "Hibernate.c3p0.idle_test_period">30000</ Property>        < Propertyname= "Hibernate.c3p0.acquire_increment">2</ Property>

Database Connection Pool

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.