Database Connection Pool

Source: Internet
Author: User
Tags connection pooling

Manually writing a connection pool requires implementing the Java.sql.DataSource interface. Two overloaded getconnection methods are defined in the DataSource interface: (JDK API)

Connection getconnection ()

Connection getconnection (string Username, string password)

Steps to implement the DataSource interface and implement the connection pooling functionality:

1. Create a connection to the database in bulk in the DataSource constructor and add the created connection to the LinkedList object.

2. Implement the Getconnection method, and let the Getconnection method take a connection from LinkedList back to the user each time it is called.

3. When the user finishes using connection and calls the Connection.close () method, the collection object should ensure that it returns itself to LinkedList instead of returning the conn to the database.

4. Collection The difficulty of programming here is to ensure that you return to LinkedList.

So in order for the connection to be returned to the LinkedList collection instead of being returned to the database, the connection Close method must be enhanced

Enhanced Close method, Conn.close ()
In practice, there are three ways to enhance an object's approach when it doesn't meet development needs
1. Write a Connecton subclass that overrides the Close method to enhance the Close method
2. Packaging design mode
3. Programming with dynamic agent AOP for facets

This can not be done with subclasses, because connection contains a lot of other information, the program will also use the connection of other information, so if the method of sub-class is basically impossible, it is equivalent to re-write the JDBC driver.

Package design mode enhance the Close method step:

1. Define a class that implements the same interface as the one being enhanced
2. Define a variable in the class, remembering the object being enhanced
3. Define a constructor to receive the enhanced object
4. Overlay the method you want to enhance
5. For methods that do not want to be enhanced, call the target object (the object being enhanced) directly

classMyConnectionImplementsconnection{PrivateConnection Conn;  Publicmyconnection (Connection conn) { This. conn =Conn; }         Public voidClose () {List.add ( This. conn); }         Public voidClearwarnings ()throwsSQLException { This. Conn.clearwarnings (); }

.......

The best solution is a dynamic proxy. Use interception technology. AOP, tangent-oriented programming

Open Source database connection pool: Database connection pool also called data source

Many Web servers (Weblogic, WebSphere, Tomcat) now provide the implementation of Datasoruce , which is the implementation of the connection pool.

Usually we put the implementation of DataSource, according to its English meaning is called the data source, the data source contains the database connection pool implementation.


There are also open source organizations that provide a separate implementation of the data source:
  DBCP Database Connection Pool
C3P0 Database Connection Pool

The actual application does not need to write the connection database code, directly from the data source to obtain the database connection. Programmers should also use the implementation of these data sources as much as possible to improve the database access performance of the program.

Tomcat's built-in connection pool is Dbcp,tomcat Apache, and DBCP is Apache.

DBCP Data Source:

DBCP is an open source connection pool implementation under the Apache Software Foundation, using the 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.

Dbcpconfig.properties encapsulates some of the configuration information for the DBCP data source, including database connections, connections, and so on.
Typically placed under the SRC folder
 Public classJDBCUTILS_DBCP {Private StaticDataSource ds =NULL; Static{        Try{InputStream in= jdbcutils_dbcp.class. getClassLoader (). getResourceAsStream ("Dbcpconfig.properties"); Properties prop=NewProperties ();                        Prop.load (in); Basicdatasourcefactory Factory=Newbasicdatasourcefactory (); DS=Factory.createdatasource (prop); }Catch(Exception e) {Throw NewExceptionininitializererror (e); }    }     Public StaticConnection getconnection ()throwssqlexception{returnds.getconnection (); //Connect from the connection pool, this connection must also be enhanced, as the connection is exhausted and also back to the connection pool.     }             Public Static voidrelease (Connection conn,statement st,resultset rs) {if(rs!=NULL){            Try{rs.close (); //throw New}Catch(Exception e) {e.printstacktrace (); } RS=NULL; }        if(st!=NULL){            Try{st.close (); }Catch(Exception e) {e.printstacktrace (); } St=NULL; }        if(conn!=NULL){            Try{conn.close (); }Catch(Exception e) {e.printstacktrace (); }        }                    }}    

In development, connections can be obtained through the connection pool above, freeing the connection.

C3P0 data Source:Spring's built-in connection pool is c3p0

Import two jar packages from c3p0

C3p0.....jar

Mchang-commons.jar

C3p0-config.xml Connection pool configuration files, typically placed in the SRC directory, details view C3P0 's documentation

<?xml version= "1.0" encoding= "UTF-8"?><c3p0-config> <default-config> <property name= "Driverclass" >com.mysql.jdbc.Driver</property> <property name= "Jdb CUrl ">jdbc:mysql://localhost:3306/day16</property><property name= "User" >root</property> <property name= "password" >root</property> <property name= "acquireincrement" >5</property> <property name= "Initialpoolsize" >10</proper ty> <property name= "minpoolsize" >5</property> <property name= "Maxpoolsize" >20</prope Rty> </default-config> <named-config name= "FLX" > <property name= "Driverclass" >com.mysql.jdbc.driver</propert y> <property name= "Jdbcurl" >jdbc:mysql://localhost:3306/day16</property><property name= "User" >root</property> <property name= "password" >root</property> <        Property Name= "Acquireincrement" >5</property> <property name= "Initialpoolsize" >10</property>     <property name= "Minpoolsize" >5</property> <property name= "Maxpoolsize" >20</property> </named-config></c3p0-config>

 Public classjdbcutils_c3p0 {Private StaticCombopooleddatasource ds =NULL; Static{        Try{DS=NewCombopooleddatasource (); }Catch(Exception e) {Throw NewExceptionininitializererror (e); }    }     Public StaticConnection getconnection ()throwssqlexception{returnds.getconnection (); }             Public Static voidrelease (Connection conn,statement st,resultset rs) {if(rs!=NULL){            Try{rs.close (); //throw New}Catch(Exception e) {e.printstacktrace (); } RS=NULL; }        if(st!=NULL){            Try{st.close (); }Catch(Exception e) {e.printstacktrace (); } St=NULL; }        if(conn!=NULL){            Try{conn.close (); }Catch(Exception e) {e.printstacktrace (); }        }                    }}    

To configure the Tomcat database connection pool:

With Tomcat, you don't have to join a third-party connection pool, and Tomcat has a connection pool if you want Tomcat

To create a connection pool for your application, you need to configure Tomcat.

<Context>  <resource name= "Jdbc/datasource" auth= "Container"            type= "Javax.sql.DataSource "Username=" root "password=" root "            driverclassname=" com.mysql.jdbc.Driver "           url=" jdbc: Mysql://localhost:3306/jdbc "            maxactive=" 8 "maxidle=" 4 "/></context>

As long as Tomcat is configured above, Tomcat creates a connection pool for your application when it starts, and Tomcat binds the created connection pool to a URI in jndi form.

Name= "Jdbc/datasource", as long as the use of this name in Jndi to retrieve it.

The above configuration can be server.xml in the tomcat-config.

You can also create a new context.xml configuration under the Webroot-meta-inf folder.

You can refer to the Jndi-configration in Tomcat's homepage

In the program, you can use Jndi to connect to the connection pool.

Context initctx = new InitialContext ();
Context Envctx = (context) initctx.lookup ("java:comp/env");
DataSource = (DataSource) envctx.lookup ("Jdbc/datasource");

Special reminder: In this configuration, the drive jar file needs to be placed under Tomcat Lib

JNDI (Java naming and directory Interface), Java Naming and directory interface, which corresponds to the javax.naming package in J2SE,

The main purpose of this set of APIs is that it can put Java objects in a container (Jndi container) and a Java object in the container name, later the program wants to get Java objects, simply by name retrieval.

Its core API is the context, which represents the Jndi container, whose lookup method is to retrieve the object that corresponds to the name in the container.

 Public classJdbcutils_tomcat {Private StaticDataSource ds; Static {        Try{Context Initctx=NewInitialContext (); Context Envctx= (Context) initctx.lookup ("Java:comp/env")); DS= (DataSource) envctx.lookup ("Jdbc/employeedb"); } Catch(Exception e) {Throw NewRuntimeException (e); }    }     Public StaticConnection getconnection ()throwssqlexception{returnds.getconnection (); }}

You can use the above tool class to connect to a tomcat built-in data source in your program.

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.