Java Web Architecture Series Knowledge (1) Database Connection Pool

First, the initial database connection

 When I first started to learn how to operate databases in Java, I used native jdbc to connect to the database in my student days, and did a series of manual actions for each database operation business.

(1) JDBC driver registration

(2) Establish a database connection

(3) Create a database operation handle

(4) Use ResultSet to execute the SQL statement of the handle

(5) Perform subsequent value assembly actions on ResultSet

(6) Release the database connection

The code example is as follows:

    /**
     * Test connection, no connection pool
     */
    private void testConnOrigin(){
        try{
            long start = System.currentTimeMillis();
            // 1. static block register jdbc.driver
            Class.forName("com.mysql.jdbc.Driver");

            // 2. using user/pwd to connect mysql
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/du?user=root&password=admin");

            long end = System.currentTimeMillis();

            System.out.println("conn-time: " + (end - start));
            // 3. declare handler
            Statement state = conn.createStatement();

            // 4. execute sql to store in resultSet
            String sql = "select * from server";
            ResultSet result = state.executeQuery(sql);

            // 5. opr resultSet
            while(result.next()){
                System.out.println(result.getString("id"));
            }
            conn.close();
        }catch(Exception e){
            System.out.println(e.toString());
        }finally {

        }

    }
Among them, the length of the test to create a database connection is about: conn-time: 669ms, different test machine environments may have different errors, but establishing a database connection and closing a database connection does consume time and program performance.
What resources do database connections consume:
(1) When establishing a database connection: Three-way handshake to establish a TCP connection
(2) To verify the username and password, etc., an authentication message needs to be sent
(3) When the query starts, you need to set the variables of the connection, such as character settings, etc.
(4) When closing the database connection: wave four times to disconnect the TCP connection
(5) Holding too many database connections will cause a large consumption of memory on the database client and server side

Second, the database connection pool
1. Core idea:
(1) Connection multiplexing: avoid repeatedly establishing and closing database connections
(2) Encapsulating JDBC: unified operation and simplicity
2. Solution:
(1) Resource pool, container class: storage and management of all database connections
(2) Allocation and release strategy:


3. Configure the policy: (How to configure?)
(1) The number of initial connections: if it is too small, too many connections will be created later, and if it is too large, the startup and creation time will be long.
(2) Maximum number of connections:
4. Key points:
(1) Reference counting:
Principle: Each connection is used, the reference count is +1, if the maximum reference count size is exceeded, the connection is destroyed.
Reason: Each database connection will use a large chunk of memory when it is used for operations. When it exceeds a certain number of times, the connection needs to be destroyed and the memory will be released.
(2) Two-pole connection pool:
(3) Transaction management:
Principle: Each transaction has an exclusive connection
Reason: multiple transactions share a connection, there will be many ACID troubles
(4) Unified external operation interface
(5) Database connection thread safety
Principle: Thread-safe or thread-safe containers such as synchronized, BlockQueue, ThreadLocal, CopyOnWriteArrayList can be used to ensure
5. Implementation of the basic principle of database connection pool
A better way to solve the time consumption and performance consumption of database connection and closing database connection is database connection pool. The basic principle is very simple:
(1) At the beginning of the program, create a minimum number of database connections and place them in a container class such as BlockQueue.
(2) When you need to use the database, call getConnection, take out the idle connection object from the connection pool, and use it. (involving allocation release strategy)
(3) After use, return the database connection to the database connection pool to achieve the function of database connection multiplexing.
6. Specific code: omitted




Guess you like

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