Use of the Java database connection pool DBCP

Source: Internet
Author: User

In recent years, with the rapid development of internet/intranet network technology and the rapid popularization in the world, computer

Applications have been transferred from a traditional desktop app to a web app. The 3-tier development model based on B/s (browser/server) architecture gradually replaces the development model of C/s (client/server) architecture, and becomes a popular technology for developing enterprise applications and e-commerce.

In the Java language, JDBC (Java database Connection) is a bridge between application and database communication,

That is, the Java language accesses the database through JDBC technology. JDBC is an "open" scenario that provides a standard application design Interface for database application developer ﹑ Database foreground tool developers, enabling developers to write complete database applications in a pure Java language. JDBC provides two APIs, namely the developer-oriented API and the JDBC driver API for the underlying, which is primarily connected to the database through direct JDBC driver and Jdbc-odbc bridge drivers.

In general, the process of accessing a database by a Java application is:

① loading the database driver;

② database connection through JDBC;

③ Access database, execute SQL statement;

④ Disconnect the database.

As a database access technology, JDBC has the advantages of simple and easy to use. However, there are many problems with using this pattern for Web application development: First, the database connection is established for each Web request. Establishing a connection is a time-consuming activity that takes 0.05s~1s times each time, and the system allocates memory resources. This time for one or several database operations, you may not feel how much overhead the system has. But for today's web applications, especially large e-commercewebsite, and it's normal to have hundreds of or even thousands of people online. In this case, the frequent database connection operation is bound to occupy a lot of system resources, the response speed of the site must be reduced, serious or even cause a server crash. is not alarmist, this is restricting the development of some e-commerce website technology bottleneck problem. Second, for each database connection, you have to disconnect after use. Otherwise, if the program fails to shut down, it will cause a memory leak in the database system and will eventually have to restart the database. Also, this development does not control the number of connection objects being created, and system resources are allocated without consideration, such as too many connections, which can lead to memory leaks and server crashes.

As can be seen from the above analysis, the root of the problem lies in the Database inefficient management of connected resources. We know that

For shared resources, there is a well-knownDesignPatterns: Resource pools (Resource pool). This model is to solve the problem caused by the frequent allocation of resources ﹑ release. To solve the above problems, the database connection pooling technology can be adopted. 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. More importantly, we can monitor the number of connections in the database through the connection pool management mechanism ﹑ usage, provide the basis for system development ﹑ test and performance adjustment. The DBCP database connection pool code is used as follows:

Package Util;import Java.sql.connection;import Java.sql.preparedstatement;import java.sql.resultset;import Org.apache.commons.dbcp.basicdatasource;import org.apache.log4j.logger;/** * Description: Database Connection Pool class * @filename Datasourcefactory.java * @date August 21, 2013 19:47:21 * @author Herman.xiong * @version 1.0 * Copyright (c) company,inc . All rights Reserved. */public class Datasourcefactory {private static Logger log = Logger.getlogger (datasourcefactory.class);p rivate static Basicdatasource bs = null;public static String driver,url,username,password;/** * Create data source * @return */public static Basicdat Asource Getdatasource () throws Exception{if (Bs==null) {log.info ("Database connection information: [Driver:" +driver+ ", url:" +url+ ", UserName:" +username+ ", Password:" +password+ "]"); bs = new Basicdatasource (); Bs.setdriverclassname (driver); Bs.seturl (URL); Bs.setusername (UserName); Bs.setpassword (password); bs.setmaxactive (200);//Set Maximum concurrent number bs.setinitialsize (30);// When the database is initialized, the number of connections created is bs.setminidle (50);//minimum number of idle connections bs.setmaxidle (200);//Database Maximum ConnectionsBs.setmaxwait (+); Bs.setminevictableidletimemillis (60*1000);//idle connection released after 60 seconds Bs.settimebetweenevictionrunsmillis (5*60*1000);//5 minute detects if there are dead threads Bs.settestonborrow (true);} return BS;} /** * Release data source */public static void Shutdowndatasource () throws Exception{if (Bs!=null) {bs.close ();}} /** * Get database connection * @return */public static Connection getconnection () {Connection con=null;try {if (bs!=null) {con= Bs.getconnection ();} Else{con=getdatasource (). getconnection ();}} catch (Exception e) {log.error (E.getmessage (), e);} return con;}  /** * Close connection */public static void Closecon (ResultSet rs,preparedstatement ps,connection con) {if (rs!=null) {try {rs.close ();} catch (Exception e) {log.error ("Close result set resultset exception! "+e.getmessage (), E);}} if (ps!=null) {try {ps.close ()} catch (Exception e) {log.error ("Precompiled SQL Statement object PreparedStatement off exception! "+e.getmessage (), E);}} if (con!=null) {try {con.close ();} catch (Exception e) {log.error ("Close Connection object connection exception! "+e.getmessage (), E);}}}}


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.