Java DataBase Connectivity (JDBC) database connection pooling principle analysis and implementation

First, direct access to the application database connection disadvantages

  Each time a user request requires a link to the database, and create database connections typically consume a relatively large resources, creation time is longer. Assuming that the site one day 100,000 visits, database server, you need to create 100,000 connections, a great waste of resources database, and the database server can easily cause memory overflow, extension machine.

Second, the use of database connection pool performance optimizer

The basic idea of the database connection pool of

  database connections is a key limited and expensive resources, which is reflected especially in a multi-user web application. Management of database connections can significantly affect the scalability of the entire application and robustness, affect the performance of the program. database connection pool formally proposed for this problem. database connection pool is responsible for the distribution, management and release of database connections, which allows an application to reuse an existing database connection, rather than re-establish One.

  Database connection pool at initialization creates a certain number of database connections into the connection pool, the number of these database connection is made to set the minimum number of database connections, whether these database connection is used, connection pooling will have to ensure that at least has a number of connections so much. maximum database number of connection pool defines the maximum number of connections this connection pool can be occupied, when the number of connections requested by the application to the connection pool exceeds the maximum number of connections, these requests would be added to the waiting queue . in

setting the minimum number of connections and the maximum number of connections to the database connection pool to take into account the following factors: minimum number of connections : a database connection pool is kept, so if your application uses a database connection is not the amount of the there will be a large number of database connection resources are wasted. the maximum number of connections : is the maximum number of connections the connection pool can apply, if the database connection requests exceeded the number of database connection requests will be added to the back of the queue, which will affect future database operation   If the minimum number of connections and the maximum number of connections vary widely: so Connect request will profit, after more than a minimum number of connections equivalent to a connection request to establish a connection to the new database. However, these larger than the minimum number of connections are finished using the database connection is not immediately released, he will be placed waiting for the connection pool reused or released after a timeout space.

  
  

 

Write database connection pool

 

DBManage This class is used to read the configuration file properties, create a connection object, the connection object management

 

. 1  Import java.io.IOException;
 2  Import the java.sql.Connection;
 . 3  Import the java.sql.DriverManager;
 . 4  Import the java.sql.ResultSet;
 . 5  Import java.sql.SQLException;
 . 6  Import the java.sql.Statement;
 . 7  Import the java.util.Properties;
 . 8  
. 9  Import orm.bean.Configuration;
 10  Import orm.pool.DBConnPool;
 . 11  
12 is  / ** 
13 is  * according to configuration information, maintaining connection object management
 14  * @author Haidnor
 15  *
 16  * / 
. 17 @SuppressWarnings ( "All" )
 18 is  public  class DBManage {
 . 19      / ** 
20 is       * configuration information
 21 is       * / 
22 is      Private  static the Configuration the conf;
 23 is      
24      / ** 
25       * connection pool object
 26 is       * / 
27      Private  static DBConnPool the pool = null ;
 28      / ** 
29       * initialize, load the specified file
 30       * / 
31 is      static {
 32          the Properties Pros = new new the Properties ();    
 33 is         
34 is          the try {
 35              pros.load (Thread.currentThread () getContextClassLoader () getSystemResourceAsStream ( "the database.properties.". ));
 36          } the catch (IOException E) {
 37 [              e.printStackTrace ();
 38 is          }
 39          the conf = new new the Configuration ();     // read the configuration file, the information in the configuration file stored in the configuration object 
40          conf.setDriver (pros.getProperty ( "Driver" ));
 41 is          conf.setUrl (pros.getProperty ( "URL" )) ;
 42 is          conf.setUser (pros.getProperty ( "User" ));
 43 is         conf.setPassword(pros.getProperty("password"));
44         conf.setUsingDB(pros.getProperty("usingDB"));
45         conf.setSrcPath(pros.getProperty("srcPath"));
46         conf.setPoPackage(pros.getProperty("poPackage"));
47         conf.setQueryClass(pros.getProperty("queryClass"));
48         conf.setPoolMinSize(Integer.parseInt(pros.getProperty("poolMinSize")));
49         conf.setPoolMaxSize(Integer.parseInt(pros.getProperty("poolMaxSize")));
     * Connection object obtained in the connection pool
53/ **52 is51 is    }
50  
     
 54      * @return
55      */
56     public static Connection getConnetion() {
57         if(pool == null) {
58             pool = new DBConnPool();            
59         }
60         return pool.getConnection();
61     }
62     
63     /**
64      * 创建新的Connection对象
65      * @return
66      */
67     public static Connection createConnetion() {
68         try {
69             Class.forName (conf.getDriver ());
 70              return DriverManager.getConnection (conf.getUrl (), conf.getUser (), conf.getPassword ());      // currently a direct connection, later joined connection pool treatment to improve efficiency 
71 is          } the catch (Exception E) {
 72              e.printStackTrace ();
 73 is              return  null ;
 74          }
 75      }
 76      
77      / ** 
78       * Close the Statement connection database connected the ResultSet
 79       * @param RS
 80       * @param PA
 81       * @ param conn
82      */
83     public static void close(ResultSet rs,Statement pa,Connection conn){
84         if(conn != null){
85             pool.close(conn);
86         }
87     }
88     
90     /**
91      * 返回Configuration对象
92      * @return Configuration对象
93      */
94     public static Configuration getConf(){
95         return conf;
96     }
97 }

 

Database connection pool class DBManage, a plurality of objects stored in a Connection List collection. Before initialization, the object automatically in accordance with the connection pool configuration file set the minimum number of objects to create a plurality of Connection set list.

After using the Connection object can be set directly from the list. Close Connection objects no longer close () method, but the Connection object list and put back in the collection.

 1 import java.sql.Connection;
 2 import java.sql.SQLException;
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 import orm.core.DBManage;
 7 
 8 /**
 9  * 连接池类
10  * @author Haidnor
11  *
12  */
13 
14 public class DBConnPool {
15     
16     /**
17      * 连接池对象
18      */
19     private List<Connection>the pool; 
 20 is      
21 is      / ** 
22 is       * the maximum number of connections
 23 is       * / 
24      Private  static  Final  int POOL_MAX_SIZE = DBManage.getConf () getPoolMaxSize ();.
 25      
26 is      / ** 
27       * minimum number of connections
 28       * / 
29      Private  static  Final  int = POOL_MIN_SIZE DBManage.getConf () getPoolMinSize ();.
 30      
31 is      / ** 
32       * initialize the connection pool, so that the number reaches a minimum connection pool
 33 is       * / 
34 is      Private  void initPool () {
 35          IF (the pool ==null ) {
 36              the pool = new new the ArrayList <Connection> ();
 37 [          }
 38 is          the while (pool.size () <= DBConnPool.POOL_MIN_SIZE) {
 39              pool.add (DBManage.createConnetion ());
 40          }
 41 is      }
 42 is      
43 is      / ** 
44       * out a connection object from the connection pool
 45       * @return 
46 is       * / 
47      public  the synchronized connection the getConnection () {
 48          int LAST_INDEX = pool.size () -. 1 ;
 49         Connection connection = pool.get(last_index);
50         pool.remove(last_index);
51         return connection;
52     }
53     
54     /**
55      * 将连接放回池中
56      */
57     public synchronized void close(Connection connection) {
58         if(pool.size() >= POOL_MAX_SIZE){
59             try {
60                 if(connection != null){
61                     connection.close();
62                 }
63             } catch (SQLException e) {
64                 e.printStackTrace();
65             }
66         }else{
67             pool.add(connection);
68         }
69     }
70     
71     
72     public DBConnPool(){
73         initPool();
74     }
75     
76 }

Finally, create a test class. Respectively, using a database connection pool Connection object and direct a new Connection objects to database tables 3000 query test

Using a connection pool takes 952 milliseconds, without connection pooling time-consuming 12,742 milliseconds.

Import java.util.List; 

Import orm.core.MySqlQuery;
 Import orm.po.User_yinbiao1; 

public  class the Test {
     // without connection pool Processed 12,742 milliseconds
     // plus connection pool time: 952 msec 
    public  static  void main ( String [] args) {
         Long A = System.currentTimeMillis ();
         for ( int I = 0; I <3000; I ++ ) { 
            testQueryRows ();             
        } 
        Long B = System.currentTimeMillis (); 
        System.out.println ( " database connection pool run time: "+ (b - a) +" msec " ); 
    }
    
    public static void testQueryRows() {
        List list = new MySqlQuery().queryRows("SELECT * FROM user_yinbiao1", User_yinbiao1.class, new Object[] {});
        User_yinbiao1 user =  (User_yinbiao1)list.get(2);
    }

}

 

Guess you like

Origin www.cnblogs.com/Haidnor/p/11204471.html