当前位置:网站首页>JDBC | Chapter 6: simple use of database connection pool
JDBC | Chapter 6: simple use of database connection pool
2022-06-29 06:23:00 【Mr. dujiu QAQ】
One . Why use connection pools
Database connection is a key limited and expensive resource , This is especially prominent in multi-user web applications . A database connection object corresponds to a physical database connection , Each operation opens a physical connection , Close the connection after use , This results in poor performance of the system .
The solution to the database connection pool is to establish enough database connections when the application starts , These connections form a connection pool ( In short : In a “ pool ” There are a lot of semi-finished database connection objects in it ), The application dynamically requests connections in the pool 、 Use and release . For more concurrent requests than the number of connections in the connection pool , You should queue in the request queue . And the application can be based on the utilization of connections in the pool , Dynamically increase or decrease the number of connections in the pool .
Connection pooling technology reuses as many memory consuming resources as possible , It saves a lot of memory , Improve the service efficiency of the server , Be able to support more customer service . By using the connection pool , Will greatly improve the efficiency of the program , meanwhile , We can monitor the number of database connections through its own management mechanism 、 Usage, etc .
Two . Usually use jdbc disadvantages
Steps to not use database connection pooling :
- TCP Three handshakes to establish a connection
- MySQL Three handshakes for authentication
- real SQL perform
- MySQL The closing of the
- TCP Four handshakes close
You can see , In order to carry out a clause SQL, But there's a lot more network interaction
advantage :
Implement a simple
shortcoming :
- The Internet IO More
- Database load is high
- Long response time and QPS The lower
- Applications frequently create and close connections , This results in more temporary objects ,GC frequent
- After closing the connection , There will be a lot of TIME_WAIT Of TCP state ( stay 2 individual MSL Then close )
Use the connection pooling process
The first time I visited , Connection required . But after that visit , Will reuse the connection created before , Direct execution SQL sentence .
advantage :
- Less network overhead
- There will be a substantial improvement in the performance of the system
- There's no trouble TIME_WAIT state
The first time I visited , Connection required . But after that visit , Will reuse the connection created before , Direct execution SQL sentence .
advantage :
- Less network overhead
- There will be a substantial improvement in the performance of the system
- There's no trouble TIME_WAIT state
3、 ... and . How database connection pools work
The working principle of connection pool is mainly composed of three parts , Respectively
- Establishment of connection pool
- Connection management in connection pool
- Closure of connection pool
First of all 、 Establishment of connection pool .
Generally, when the system is initialized , The connection pool will be established according to the system configuration , And created several connection objects in the pool , So that you can get from the connection pool . Connections in a connection pool cannot be created or closed at will , This avoids the overhead caused by the random establishment and closure of connections .
Java Many container classes are provided in to facilitate the construction of connection pools , for example Vector、Stack etc. .
second 、 Connection pool management .
Connection pool management policy is the core of connection pool mechanism , The allocation and release of connections in the connection pool have a great impact on the performance of the system . Its management strategy is :
When a customer requests a database connection , First, check whether there are free connections in the connection pool , If there is an idle connection , Then assign the connection to the customer ; If there is no free connection , Check whether the current number of connections has reached the maximum number of connections , If not, re create a connection to the requesting customer ; If it is reached, wait according to the set maximum waiting time , If the maximum waiting time is exceeded , Throw an exception to the customer .
When the customer releases the database connection , First judge whether the number of references of the connection exceeds the specified value , If it exceeds, delete the connection from the connection pool , Otherwise, keep serving other customers .
This strategy ensures the effective reuse of database connections , Avoid frequent build ups 、 Release the system resource overhead caused by connection .
Third 、 Closure of connection pool .
When the application exits , Close all connections in the connection pool , Release connection pool related resources , This process is just the opposite of creating .
Four . Points to note about connection pooling
1、 Concurrency issues
In order to make the connection management service have the greatest commonality , You have to think about a multithreaded environment , That is, concurrency .
This problem is relatively easy to solve , Because each language itself provides support for concurrency management, such as java,c# wait , Use synchronized(java)lock(C#) Keyword to ensure that threads are synchronized .
2、 Transaction processing
We know , Transactions are atomic , At this point, the operation of the database is required to comply with “ALL-OR-NOTHING” principle , That is, for a group SQL You can either do it all , Or not at all .
We know when 2 Threads share a connection Connection object , And each has its own business to deal with , It's a big headache for connection pooling , Because even if Connection Class provides corresponding transaction support , However, we are still not sure that the database operation corresponds to that transaction , It's because we have 2 It is caused by two threads operating on transactions .
For this purpose, we can use each transaction to exclusive one connection , Although this method is a bit wasteful of connection pool resources, it can greatly reduce the complexity of transaction management .
3、 Allocation and release of connection pool
Allocation and release of connection pool , It has a great influence on the performance of the system . Reasonable distribution and release , It can improve the reusability of the connection , This reduces the overhead of establishing new connections , At the same time, it can also speed up the access speed of users .
For connection management, a List. That is, put all the created connections into the List Unified management in China . Whenever a user requests a connection , The system checks this List Is there any connection that can be assigned in . If so, assign him the most suitable connection , If not, throw an exception to the user .
4、 Configuration and maintenance of connection pool
How many connections should be placed in the connection pool , To optimize the performance of the system ?
The system can set the minimum number of connections (minConnection) And maximum connections (maxConnection) And other parameters to control the connections in the connection pool . For example , The minimum number of connections is the number of connections created by the connection pool at system startup . If you create too many , The system starts slowly , However, the response speed of the system will be very fast after creation ; If you create too few , The system starts up very quickly , The response is slow . such , It can be used during development , Set a small minimum number of connections , It will be developed quickly , When the system is actually used, a larger , Because it is faster to visit customers . The maximum number of connections is the maximum number of connections allowed in the connection pool , How much is the specific setting , It depends on the number of visits to the system , It can be obtained from the software requirements .
How to ensure the minimum number of connections in the connection pool ? There are two strategies, dynamic and static . Dynamic means to detect the connection pool every certain time , If the number of connections is less than the minimum number of connections , Then add the corresponding number of new connections , To ensure the normal operation of the connection pool . Static is to check if there are not enough idle connections .
5、 ... and . Use of database connection pool
durid
package cn.soboys.kenx.datasource;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.util.Properties;
/* * jdbc Through data connection pool Druid Get database connection */
public class DruidDatasource {
// Configure through the properties file , The data source factory does not need to manually configure a single property
public Connection getConnectionByDuridPoolProperties() {
Properties prop = new Properties();
try {
prop.load(new FileInputStream("src/main/resources/durid.properties"));
// Get connection pool object
DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
System.out.println(" Database connection successful ");
return dataSource.getConnection();
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
// Through code configuration
public Connection getConnectionByDBCPPoolCode() {
try {
DruidDataSource bds=new DruidDataSource();
bds.setUrl("jdbc:mysql://localhost:3306/kenx_test?characterEncoding=utf-8");
bds.setDriverClassName("com.mysql.cj.jdbc.Driver");
bds.setUsername("root");
bds.setPassword("root");
bds.setInitialSize(5);
Connection conn = bds.getConnection();
System.out.println(" Database connection successful ");
return conn;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
Basically, it is completely quoted from
边栏推荐
- 2022.02.15
- How to insert pseudo code into word documents simply and quickly?
- Hyperledger Fabric 2. X custom smart contract
- 3 frequently tested SQL data analysis questions (including data and code)
- Regular expressions for shell script values
- Slot
- Ti Click: quickly set up tidb online laboratory through browser | ti- team interview can be conducted immediately
- Analysis comp122 the Caesar cipher
- ICLR is going to have a big discussion on the deep generation model. Max welling and the winner of the AAAI million dollar award are here. Bengio is one of the organizers
- Call the computer calculator and use it to convert several base numbers
猜你喜欢

Installing modules in pycharm

Summary of redis basic knowledge points

Rich material libraries make modeling easy and efficient for developers
![[chromium] win10 vs2019 environment chromium configuration and compilation.](/img/20/428e6b22ed6955a732dd14d5ff0e3d.jpg)
[chromium] win10 vs2019 environment chromium configuration and compilation.

Use of sed in shell script

Design risc-v processor from scratch -- data adventure of five stage pipeline
![ASP. Net core 6 framework unveiling example demonstration [03]:dapr initial experience](/img/fd/4c24e10fc91a7ce7e709a0874ba675.jpg)
ASP. Net core 6 framework unveiling example demonstration [03]:dapr initial experience

Fresnel diffraction with rectangular aperture based on MATLAB

Ctrip launched the "3+2" office mode. Are you sour?
![[high concurrency] deeply analyze the callable interface](/img/17/93056547aa1a2b342e1b159b7c41c2.jpg)
[high concurrency] deeply analyze the callable interface
随机推荐
51 single chip microcomputer learning notes 7 -- Ultrasonic Ranging
Boost the digital economy and face the future office | the launch of the new version of spreadjsv15.0 is about to begin
Meta metauniverse female safety problems occur frequently. How to solve the relevant problems in the metauniverse?
Skills of writing test cases efficiently
2022-01 Microsoft vulnerability notification
Convert data frame with date column to timeseries
2022 recommended REITs Industry Research Report investment strategy industry development prospect market analysis (the attachment is a link to the online disk, and the report is continuously updated)
How does MySQL implement distributed locks?
Case of single file component files
Where is the Gcov symbol- Where are the gcov symbols?
QT writing map comprehensive application 58 compatible with multi browser kernel
[C language series] - initial C language (4)
2022.02.14
Will the order of where conditions in MySQL affect the union index? Will where 1 =1 affect the use of the index? Does where 1 =1 affect the use of indexes?
Maximum ascending subarray sum of leetcode simple problem
Design and practice of kubernetes cluster and application monitoring scheme
Jenkins operation Chapter 6 mail server sending build results
Difference between URI and URL
Fresnel diffraction with rectangular aperture based on MATLAB
Devops development, operation and maintenance Basics: using Jenkins to automatically build projects and notify by email