The principle of database connection pool



The principle of database connection pool

   

     This time we take the method of technological evolution to talk about the technology emergence process and principle of database connection pool, as well as the most popular open source database connection pool jar package.

1. How did we perform database operations in the early days

       1. Principle: Generally speaking, the process of java application accessing the database is:

   ① Load the database driver;

   ② Establish a database connection through jdbc ;

   ③ Access the database and execute the sql statement;

   ④ Disconnect the database connection.

       2. Code 

       // Query all users

Public void FindAllUsers(){  
       //1、装载sqlserver驱动对象  
       DriverManager.registerDriver(new SQLServerDriver());               
       //2、通过JDBC建立数据库连接  
       Connection con =DriverManager.getConnection("jdbc:sqlserver://192.168.2.6:1433;DatabaseName=customer", "sa", "123");              
       //3、创建状态  
       Statement state =con.createStatement();             
       //4、查询数据库并返回结果  
       ResultSet result =state.executeQuery("select * from users");             
       //5、输出查询结果  
       while(result.next()){  
              System.out.println(result.getString("email"));  
       }              
       //6、断开数据库连接  
       result.close();  
       state.close();  
       con.close();  
 }  


3. Analysis

       In the process of program development, there are many problems: First, a database connection must be established for each web request. Establishing a connection is a time-consuming activity that takes 0.05s to 1s each time, and the system also allocates memory resources. This time for one or several database operations may not feel much overhead to the system. But for today's web applications, especially large e-commerce sites, it is normal for hundreds or even thousands of people to be online at the same time. In this case, frequent database connection operations will inevitably occupy a lot of system resources, the response speed of the website will definitely decrease, and even cause the server to crash. Not alarmist, this is the technical bottleneck restricting the development of some e-commerce websites. Secondly, for each database connection, it must be disconnected after use. Otherwise, if the program fails to close due to an exception, it will cause a memory leak in the database system, and eventually the database will have to be restarted. In addition, this kind of development cannot control the number of connection objects created, and system resources will be allocated without consideration. If there are too many connections, it may also lead to memory leaks and server crashes.

       In the above user query case, if 1000 people visit at the same time, there will be continuous database connection and disconnection operations:

 

       Through the above analysis, we can see that "database connection" is a kind of scarce resource, in order to ensure the normal use of the website, it should be properly managed. In fact, after we query the database, if we do not close the connection, but temporarily store it, when others use it, we will give this connection to them. It avoids the time consumption of the operation of establishing a database connection and disconnection at one time. The principle is as follows:

2. Database connection pool evolved from technology

       It can be seen from the above analysis that the root of the problem lies in the inefficient management of database connection resources. We know that for shared resources, there is a very famous design pattern: resource pool ( resource pool ). This mode is to solve the problem caused by the frequent allocation and release of resources. In order to solve the above problems, the database connection pool technology can be used. The basic idea of ​​database connection pooling is to create a "buffer pool" for database connections. Put a certain number of connections in the buffer pool in advance. When you need to establish a database connection, you only need to take one out of the "buffer pool" and put it back after use. We can prevent the system from endlessly connecting to the database by setting the maximum number of connections in the connection pool. More importantly, we can monitor the number and usage of database connections through the management mechanism of the connection pool, providing a basis for system development, testing and performance adjustment.

       We try to develop a connection pool ourselves to provide database connection services for the above query business:

       ①Write   a class to implement the DataSource interface

       ②Create   10 connections at a time in the class constructor and save the connections in the LinkedList

       ③   Implement getConnection  to return a connection from LinkedList

       ④   Provide a method to put the connection back into the connection pool


1. Connection pool code
public class MyDataSource implements DataSource {  
          //链表 --- 实现栈结构  
          privateLinkedList<Connection> dataSources = new LinkedList<Connection>();  

          //初始化连接数量  
          publicMyDataSource() {  
                 //一次性创建10个连接  
                 for(int i = 0; i < 10; i++) {  
                        try {  
                           //1、装载sqlserver驱动对象  
                           DriverManager.registerDriver(new SQLServerDriver());  
                           //2、通过JDBC建立数据库连接  
                           Connection con =DriverManager.getConnection(  
                              "jdbc:sqlserver://192.168.2.6:1433;DatabaseName=customer", "sa", "123");  
                           //3、将连接加入连接池中  
                           dataSources.add(con);  
                        } catch (Exception e) {  
                           e.printStackTrace();  
                        }  
                 }  
          }  

          @Override  
          publicConnection getConnection() throws SQLException {  
                 //取出连接池中一个连接  
                 finalConnection conn = dataSources.removeFirst(); // 删除第一个连接返回  
                 returnconn;  
          }  

          //将连接放回连接池  
          publicvoid releaseConnection(Connection conn) {  
                 dataSources.add(conn);  
                 }  
   }  

2. Refactor our user query function using connection pooling

//查询所有用户  
Public void FindAllUsers(){  
       //1、使用连接池建立数据库连接  
       MyDataSource dataSource = new MyDataSource();  
       Connection conn =dataSource.getConnection();          
       //2、创建状态  
       Statement state =con.createStatement();             
       //3、查询数据库并返回结果  
       ResultSet result =state.executeQuery("select * from users");             
       //4、输出查询结果  
       while(result.next()){  
              System.out.println(result.getString("email"));  
       }              
       //5、断开数据库连接  
       result.close();  
       state.close();  
       //6、归还数据库连接给连接池  
       dataSource.releaseConnection(conn);  
 }  

Source: http://blog.csdn.net/shuaihj/article/details/14223015



The principle of database connection pool

   

     This time we take the method of technological evolution to talk about the technology emergence process and principle of database connection pool, as well as the most popular open source database connection pool jar package.

1. How did we perform database operations in the early days

       1. Principle: Generally speaking, the process of java application accessing the database is:

   ① Load the database driver;

   ② Establish a database connection through jdbc ;

   ③ Access the database and execute the sql statement;

   ④ Disconnect the database connection.

       2. Code 

       // Query all users

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325607358&siteId=291194637