MySQL---Database from getting started to the Great God Series (13)-basicdatasource Create datasource (dbcp Connection pool configuration)

Source: Internet
Author: User

DBCP (database connection pool), DB connection pool. is a Java Connection pool project on Apache and a connection pool component used by Tomcat. Use of DBCP alone requires 2 packages: Commons-dbcp.jar, Commons-pool.jar because establishing a database connection is a very time-consuming and resource-intensive behavior, the connection pool is pre-established with the database to make some connections, put in memory, the application needs to establish a database connection directly to the connection pool to apply for a line, run out and then put back.

First, download the required jar package

DBCP package, the current version is 2.1.1:
http://commons.apache.org/proper/commons-dbcp/download_dbcp.cgi

Pool package, current version is 2.4.2:
http://commons.apache.org/proper/commons-pool/download_pool.cgi

The Apache Commons Logging package is currently available in version 1.2:
http://commons.apache.org/proper/commons-logging/download_logging.cgi

The MySQL jar package Mysql-connector-java-5.1.39-bin is currently 5.1.39 Version:
http://dev.mysql.com/downloads/connector/j/

Demo Code:
Package CN. Hncu. DBCP;Import Java. SQL. Connection;Import Java. SQL. SQLException;Import Java. Util. Properties;Import Javax. SQL. DataSource;import org. Apache. Commons. DBCP2. Basicdatasource;import org. Apache. Commons. DBCP2. Basicdatasourcefactory;import org. JUnit. Test;public class Dbcppooldemo {//plain Java mode setting parameters, using DBCP pool @Test public void testdbcp () {Basicdatasource pool = n EW Basicdatasource ();//Connection PoolPool. Setusername("Root");Pool. SetPassword("1234");Pool. Setdriverclassname("Com.mysql.jdbc.Driver");Pool. SetUrl("Jdbc:mysql://127.0.0.1:3306/hncu?useunicode=true&characterencoding=utf-8");System. out. println(Pool. Getmaxidle());//maximum idle time. If a user gets a connection, no, how long it takes to be forcibly retractedSystem. out. println(Pool. Getmaxwaitmillis())///The maximum time the pool waits for a connection to be reclaimed before throwing an exception (when no connection is available). Set to 1 to indicate an infinite wait. System. out. println(Pool. Getinitialsize());//initialization with several connectionSystem. out. println(Pool. Getmaxtotal());//How many connection can you have?System. out. println("----------------");Pool. Setmaxtotal( -);//We can set the relevant parameters of the pool ourselves, such as the maximum number of connectionsGets the connection from its pool for (int i =0; i <; i++) {Connection con = null;try {con = Pool. getconnection();} catch (SQLException e) {E. Printstacktrace();} System. out. println(i +":"+ Con. Hashcode());}}//Set parameters by configuration file, use DBCP pool @Test public void Testpropertyfile () throws Exception {Properties p = new Properties ();P. Load(Dbcppooldemo. Class. getResourceAsStream("Dbcp.properties"));//The configuration file is put together with the class of the current classesP. Load(Dbcppooldemo. Class. getClassLoader(). getResourceAsStream("Dbcp.properties"))///config file to be placed in src (bin) root directory---classpath rootDataSource pool = basicdatasourcefactory. CreateDataSource(p);Gets the connection from its pool for (int i =0; i <; i++) {Connection con = Pool. getconnection();System. out. println(Con. Hashcode());if (i%2==0) {con. Close();}        }    }}

At first, the default connection object that can be new is 8!
And even if you just put the original connection object. Close () will not get duplicate connection object, the previous version will get back to the original Connectin object.

Connection pool-local thread management objects
 PackageCN.HNCU.DBCP;ImportJava.io.IOException;ImportJava.sql.Connection;ImportJava.sql.SQLException;ImportJava.util.Properties;ImportJavax.sql.DataSource;ImportOrg.apache.commons.dbcp2.BasicDataSourceFactory; Public  class dbcputil {    Private StaticDataSource Pool;Private StaticThreadlocal<connection> T =NewThreadlocal<connection> ();Static{Try{//Read configuration fileProperties p =NewProperties (); P.load (DbcpUtil.class.getResourceAsStream ("Dbcp.properties"));//configuration file and the class of the current classes are put togetherPool = Basicdatasourcefactory.createdatasource (p); }Catch(IOException e)        {E.printstacktrace (); }Catch(Exception e)        {E.printstacktrace (); }    }//Return to datasource--pool     Public StaticDataSourceGetdatasource(){returnPool } Public StaticConnectiongetconnection()throwssqlexception{//take from local thread management object TConnection con = t.get ();if(con==NULL) {con=pool.getconnection ();//put in TT.set (con); }returnCon }}

It is obviously more convenient to use a third-party expansion pack than to write a connection pool for yourself.

Reprint please attach the original blog link:
http://blog.csdn.net/qq_26525215

MySQL---Database from getting started to the Great God Series (13)-basicdatasource Create datasource (dbcp Connection pool configuration)

Related Article

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.