Talking about the principle of database connection pool

Source: Internet
Author: User
Tags connection pooling sql server driver

This time we take a technological evolution to talk about the process of database connection pooling technology and its rationale, and the most popular open source database connection pool jar package today.

I. How do we perform database operations in the early stages?

1. Principle: 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.

2. Code

Query All Users

[Java]View PlainCopy
  1. Public void Findallusers () {
  2. ///1, loading SQL Server driver Object
  3. Drivermanager.registerdriver (new SQLServerDriver ());
  4. ///2, database connection via JDBC
  5. Connection con =drivermanager.getconnection ("Jdbc:sqlserver://192.168.2.6:1433;databasename=customer", "              SA ", " 123 ");
  6. ///3, creation status
  7. Statement state =con.createstatement ();
  8. ///4, querying the database and returning results
  9. ResultSet result =state.executequery ("SELECT * from users");
  10. ///5, Output query results
  11. While (Result.next ()) {
  12. System.out.println (result.getstring ("email"));
  13. }
  14. //6, disconnecting the database
  15. Result.close ();
  16. State.close ();
  17. Con.close ();
  18. }

3. Analysis

In the process of program development, there are many problems: first, each Web request to establish a database connection. 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-commerce sites, there are hundreds of people or even thousands of people online is very normal. 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.

The above user query case, if there are 1000 people access, there will be continuous database connection, disconnection operation:

Through the above analysis, we can see that "database connection" is a scarce resource, in order to protect the normal use of the site, it should be properly managed. In fact, after we query the database, if we do not close the connection, but temporarily stored up, when others use, the connection to their use. It avoids the time consuming of establishing a database connection and a disconnected operation. The principle is as follows:

Two. Technology Evolved database Connection pool

As can be seen from the above analysis, the root of the problem lies in the inefficient management of database connection resources. We know that there is a well-known design pattern for shared resources: 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.

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

① writing class implements DataSource interface

② creates 10 connections at a time in the class constructor, saves the connection in LinkedList

③ implementation getconnection Returns a connection from the LinkedList

④ provides methods for putting connections back into the connection pool

1. Connection Pool Code

[Java]View PlainCopy
  1. Public class myDataSource implements DataSource {
  2. //List---implement stack structure
  3. privatelinkedlist<connection> datasources = new linkedlist<connection> ();
  4. //Initialize number of connections
  5. Publicmydatasource () {
  6. //Create 10 connections at once
  7. For (int i = 0; i < i++) {
  8. try {
  9. ///1, loading SQL Server driver Object
  10. Drivermanager.registerdriver (new SQLServerDriver ());
  11. ///2, database connection via JDBC
  12. Connection Con =drivermanager.getconnection (
  13. "Jdbc:sqlserver://192.168.2.6:1433;databasename=customer", "sa", "123");
  14. ///3, joins the connection pool
  15. Datasources.add (con);
  16. } catch (Exception e) {
  17. E.printstacktrace ();
  18. }
  19. }
  20. }
  21. @Override
  22. Publicconnection getconnection () throws SQLException {
  23. //Remove a connection from the connection pool
  24. Finalconnection conn = Datasources.removefirst (); //Delete first connection returned
  25. Returnconn;
  26. }
  27. //Put the connection back into the connection pool
  28. Publicvoid releaseconnection (Connection conn) {
  29. DATASOURCES.ADD (conn);
  30. }
  31. }

2. Using connection pooling to reconstruct our user query function

[Java]View PlainCopy
  1. Query All Users
  2. Public void Findallusers () {
  3. ///1, using connection pooling to establish a database connection
  4. myDataSource DataSource = new myDataSource ();
  5. Connection Conn =datasource.getconnection ();
  6. ///2, creation status
  7. Statement state =con.createstatement ();
  8. ///3, querying the database and returning results
  9. ResultSet result =state.executequery ("SELECT * from users");
  10. ///4, Output query results
  11. While (Result.next ()) {
  12. System.out.println (result.getstring ("email"));
  13. }
  14. ///5, disconnect the database
  15. Result.close ();
  16. State.close ();
  17. //6, returning a database connection to a connection pool
  18. Datasource.releaseconnection (conn);
  19. }

This is the principle of database connection pooling, which greatly provides the utilization of database connections and reduces the overhead of memory throughput. We are in the development process, there is no need to care about the database connection problem, there is a database connection pool to help us deal with, this time relieved. But the problem with connection pooling is more than that, let's see what else needs to be considered.

Three. There are more issues to consider in connection pooling

1, concurrency problems

In order for the connection Management Service to be the most versatile, you must consider a multithreaded environment, which is a concurrency problem. This is a relatively good problem to solve because the Java language itself provides support for concurrency management, and using the Synchronized keyword ensures that threads are synchronized. Use the method to precede the class method with the Synchronized keyword, such as:

publicsynchronized Connection getconnection ()

2, multi-database server and multi-user

For large enterprise applications, it is often necessary to connect different databases at the same time (such as connecting Oracle and Sybase). How do I connect to different databases? Our strategy is to design a connection pool management class that conforms to the singleton pattern, reading a resource file when the unique instance of the connection pool management class is created, where the resource file holds information such as the URL address of multiple databases. Creates instances of multiple connection pool classes, each of which is a connection pool for a particular database, based on the information provided by the resource file. The connection pool management class instance takes a name for each connection pool instance and manages the different connection pools with different names.

In the case of multiple users with different names and passwords for the same database, it is also possible to process the resource file by setting up multiple database connection information in the resource file with the same URL address but with a different user name and password.

3. Transaction processing

We know that transactions are atomic, which requires that the operation of the database conform to the "all-all-nothing" principle, which is to either do the whole set of SQL statements or do nothing at all.

In the Java language, the connection class itself provides support for transactions, which can be implemented by setting the Autocommit property of connection to false and then explicitly invoking a commit or Rollback method. However, for efficient connection reuse, it is necessary to provide the corresponding transaction support mechanism. Each transaction can be implemented with a single connection, which can greatly reduce the complexity of transaction management.

4. Allocation and release of connection pool

The allocation and release of the connection pool has a great impact on the performance of the system. Reasonable allocation and release can increase the reusability of the connection, thus reducing the cost of establishing a new connection and speeding up the user's access speed.

You can use the free pool for management of connections. A connection that has been created but not yet allocated is stored in a free pool at the time of creation. Whenever a user requests a connection, the system first checks that there are no idle connections in the free pool. If there is the longest established (through the container in the order of the implementation) of the connection assigned to him (the actual connection is the validity of the judgment, if available to assign to the user, if it is not available to delete the connection from the free pool, re-detect whether the free pool is still connected) If not, check whether the currently open connection pool reaches the maximum number of connections allowed for the connection pool (maxconn) if not, create a new connection and wait a certain amount of time (timeout) if it is already reached. If a connection is freed within the waiting time, the connection can be assigned to the waiting user, and a null value is returned if the wait time exceeds the scheduled time of timeout. The system only counts the connections that are already being used, and then returns them to the free pool when it is finished. For the state of idle connections, a dedicated thread timing detection can be created, which can cost a certain amount of overhead, but ensures a faster response time. You can also take a method that does not open up specialized threads, just before the allocation is detected.

5, the connection pool configuration and maintenance

How many connections should be placed in the connection pool to make the system perform optimally? The system can take control of connections in the connection pool by setting the minimum number of connections (minconn) and the maximum number of connections (maxconn). The minimum number of connections is the number of connections created by the connection pool when the system starts. If you create too many, the system starts slowly, but the system responds quickly after creation, and if you create too little, the system starts quickly and responds slowly. In this way, you can set a smaller minimum number of connections at development time, develop quickly, and set a larger size when the system is actually used, because it will be faster to access the customer. Maximum connections is the maximum number of connections allowed in the connection pool, depending on the amount of access to the system, you can find the best point by repeated testing.

How do I ensure the minimum number of connections in a connection pool? There are both dynamic and static strategies. Dynamic means that the connection pool is detected at regular intervals, and if the number of connections is found to be less than the minimum number of connections, the corresponding number of new connections is replenished to ensure the proper operation of the connection pool. Static is found when idle connection is insufficient to check again.

Four. There is a mature open source connection pool for our use in real development

Understanding the principle of the connection pool is possible, there is no need to write it all over again, that will take a lot of time, and performance and stability is not necessarily meet the requirements. In fact, there are a number of popular third-party database connection pool jar packages available for us to use. Such as:

1.Apache COMMONS-DBCP Connection Pool

Download: http://commons.apache.org/proper/commons-dbcp/

2.C3P0 Database Connection Pool

Download: http://sourceforge.net/projects/c3p0/

Talking about the principle of database 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.