Java third-party database connection pool-dbcp-c3p0-tomcat built-in connection pool

Source: Internet
Author: User
Tags connection pooling time in milliseconds

    • Connection Pooling principle

The basic idea of a database connection pool is to establish a "buffer pool" for database connections. A certain number of connections are pre-placed in the buffer pool, and when a database connection needs to be established, simply take one out of the buffer pool and put it back when you are finished. We can prevent the system from endlessly connecting to the database by setting the maximum number of connections to the connection pool.

Now popular third-party Java database Connection Pool Library

    • DBCP

it's Apache . Launch of Database Connection Pool, belongs to Apache Commons Open source project, official website: http://commons.apache.org/components.html. The purpose of Commons is to provide reusable, open source Java code.

Steps to use:

> 1 Add jar pack Commons-dbcp-1.4.jar Commons-pool-1.5.6.jar

>2 Add attribute resource file, name: dbcp.properties, file is placed in src directory

#连接设置driverClassName=Com.mysql.jdbc.Driverurl=jdbc:mysql://Localhost:3306/databaseUsername=Password=#<!--Initialize the connection--InitialSize=Ten#最大连接数量maxActive= -#<!--maximum idle connection--Maxidle= -#<!--minimum idle connection--Minidle=5#<!--timeout wait time in milliseconds of 6000 milliseconds/1000 equals 60 seconds--maxwait=60000#JDBC驱动建立连接时附带的连接属性属性的格式必须为这样: [Property name=Property ;] #注意:"User"And"Password"Two attributes are explicitly passed, so there is no need to include them here. ConnectionProperties=useunicode=true; characterencoding=utf8# Specifies the auto-commit of the connection created by the connection pool (auto-commit) state. Defaultautocommit=true#driverdefaultSpecifies that the connection created by the connection pool is read-only (read-Only ) status. #如果没有设置该值, the "setreadonly" method will not be called. (Some drivers do not support read-only mode, such as: Informix) defaultreadonly=#driverdefaultSpecifies the transaction level (transactionisolation) of the connection created by the connection pool. #可用值为下列之一: (Details visible Javadoc. ) none,read_uncommitted, read_committed, Repeatable_read, Serializabledefaulttransactionisolation=repeatable_read

> 3 Writing Data source Tool classes

 Public classDbcputil {//get the data source    Private StaticDataSource DataSource; Static{                Try{Properties Pro=NewProperties (); Pro.load (dbcputil.class. getClassLoader (). getResourceAsStream ("Dbcp.properties")); //Get the connection pool object and get the information from the configuration file to the connection pool object using theDataSource =Basicdatasourcefactory.createdatasource (PRO); } Catch(Exception e) {Throw NewExceptionininitializererror ("Connection pool initialization Failed"); }    }    //How to get connection objects     Public StaticConnection getconnection ()throwsSQLException {returndatasource.getconnection (); }    //frees the resource, where Conn.close () is putting the connection object back into the connection pool, not destroying     Public Static voidrelease (Connection conn) {if(conn!=NULL){            Try{conn.close (); } Catch(SQLException e) {e.printstacktrace (); }
} }}

    • C3p0

It 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.

C3P0 differs from DBCP: DBCP does not automatically reclaim idle connections, C3P0 has the ability to automatically reclaim idle connections.

Steps to use:

1, add jar package C3p0-0.9.1.2.jar, download location: http://www.oschina.net/p/c3p0, open source China has detailed.

2, write the configuration file c3p0-config.xml, file name fixed, can not be changed, "C3p0 Baidu Encyclopedia" has detailed configuration information, compared to the whole.

<?xml version= "1.0" encoding= "UTF-8"?><c3p0-config> <default-config>
<!--strictly use the Hump naming method, if not, it will be an error, such as Jdbcurl. --<property name= "Driverclass" >com.mysql.jdbc.Driver</property> <property name= "Jdbcurl" > Jdbc:mysql://127.0.0.1:3306/test</property> <property name= "User" ></property> <property name= "password" ></property> < !--maximum idle time, unused in 60 seconds, the connection is discarded. If 0, it will never be discarded. default:0---<property name= "MaxIdleTime" >60</property> <!--check for idle connections in all connection pools every 60 seconds. default:0---<property name= "Idleconnectiontestperiod" >60</property> <!--the interval between two connections, in milliseconds. default:1000---<property name= "Acquireretrydelay" >1000</property> <!--get 10 connections when initializing, value should be in Minpo Between Olsize and Maxpoolsize. Default:3---<property name= "Initialpoolsize" >0</property> <!--maximum idle time, unused in 30 seconds, the connection is discarded. If 0, it will never be discarded. default:0---<property name= "MaxIdleTime" >30</property> <!--the maximum number of connections left in the connection pool. Default:15--<property name= "maxpoolsize" >2</property> <property name= "Minpoolsize" >0&lt ;/property> <property name= "maxstatements" >200</property> <user-overrides user= "Test-user" > <property name= "Maxpoolsize" >10</property> <property name= "Minpoolsize" >1</property> <property name= "maxstatements" >0</property> </user-overrides> </default-config></c3p0-config>

3. Writing tool classes

 Public classC3p0util {Private StaticCombopooleddatasource CPDs =NewCombopooleddatasource (); Private Static intI=1;  Public StaticCombopooleddatasource Getcpds () {returnCPDs; }     Public StaticConnection getconnection () {Connection conn=NULL; Try{conn=cpds.getconnection ();        } Catch(SQLException e) {e.printstacktrace (); }        returnConn; }     Public Static voidClose (Connection ct) {if(ct!=NULL){            Try {Ct.close (); } Catch(SQLException e) {e.printstacktrace (); }        }    }}
    • Tomcat built-in connection pool

Development For Javaweb applications, a javaweb server must be used , and thejavaweb Server has a built-in data source.

The data source only needs to be configured on the server.

steps to configure a data source:

1.Copy "database connected jar" to Tomcat's lib directory

2. Configure the data source XML file

A) If the configuration information is written in the context.xml of the conf directory under Tomcat , Then all apps can use this data source.

b) If you are creating a context.xml in the current app's meta-inf and writing a data source, only the current app can use it.

<resource name= "jdbc/test"         auth= "Container" type= "Javax.sql.DataSource"  maxactive= "           maxidle= "maxwait="-1 "username="   "   password=" "         driverclassname=" Com.mysql.jdbc.Driver "         url=" jdbc:mysql://127.0.0.1:3306/test "/>

3. Using connection pooling

New= (DataSource) initcontext.lookup ("java:comp/env/jdbc/test"= Ds.getconnection ();

    • JNDI:java nameing Directory interface

The JNDI container is a Map

Key(String)

Value(Object)

Path+name

Object

path+ "JDBC/DAY16"

DataSource Object

Java third-party database connection pool-dbcp-c3p0-tomcat built-in 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.