Java-connection pool and DBUtils

Table of contents

1. What is database pooling

Second, why use a database connection pool

3. Database connection pool technology on the market

4. How to use Druid connection pool


1. What is database pooling

A buffer for connection objects. Responsible for application, allocation management, and connection release operations.

Second, why use a database connection pool

Instead of using the database connection pool, every time a new connection is obtained through the DriverManager , it is discarded and disconnected when it is used up. The utilization rate of the connection is too low and too wasteful. For the database server, the pressure is too much. Our database server and Java programs can't control the number of connections, which can easily cause the database server to crash.

We just want to be able to manage connections. We can create a connection pool, which can accommodate a certain number of connection objects. At the beginning, we can create some connection objects for the user first. When the user wants to get the connection object, he can directly get it from the pool without creating a new one. Yes, this also saves time. Then after the user is finished using it, put it back, and others can continue to use it. Can improve connection utilization. When the existing connections in the pool are used up, the connection pool can apply to the server for new connections and put them in the pool. Until the connections in the pool reach the "maximum number of connections", you can't apply for new connections. If you don't get a connection, you can only wait.

3. Database connection pool technology on the market

JDBC's database connection pool is represented by javax.sql.DataSource. DataSource is just an interface (usually called a data source). This interface is usually implemented by servers (Weblogic, WebSphere, Tomcat), and some open source organizations also provide implementations:

  • DBCP is a database connection pool provided by Apache. It is faster than c3p0 . However, due to its own BUG, ​​Hibernate3 no longer supports it.

  • C3P0 is a database connection pool provided by an open source organization, the speed is relatively slow, and the stability is not bad

  • Proxool is an open source project database connection pool under sourceforge. It has the function of monitoring the status of the connection pool, and its stability is a little worse than that of c3p0.

  • BoneCP is a database connection pool provided by an open source organization. It is faster than DBCP and C3P0, but it has been replaced by HikariCP .

  • Druid (Druid) is a database connection pool provided by Ali. It is said to be a database connection pool that combines the advantages of DBCP, C3P0 and Proxool.

4. How to use Druid connection pool

  1. Introduce the druid connection pool jar package

    For example: importing druid-1.1.10.jar is the same as importing the JDBC driver jar package. Note: The JDBC driver jar package must also be imported

  2. Code steps:

    • Step 1: Create a database connection pool object

    • Step 2: Set the parameters of the connection pool

    • Step 3: Get the connection object from the connection pool to use

  3. Code example:

public class TestPool {
	public static void main(String[] args) throws SQLException {
		//1、创建数据源(数据库连接池)对象
		DruidDataSource ds =new DruidDataSource();
		
		//2、设置参数
		//(1)设置基本参数
		ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
		ds.setUrl("jdbc:mysql://localhost:3306/test");
		ds.setUsername("root");
		ds.setPassword("1234");
		
		//(2)设置连接数等参数
		ds.setInitialSize(5);//一开始提前申请好5个连接,不够了,重写申请
		ds.setMaxActive(10);//最多不超过10个,如果10都用完了,还没还回来,就会出现等待
		ds.setMaxWait(1000);//用户最多等1000毫秒,如果1000毫秒还没有人还回来,就异常了
		
		//3、获取连接
		for (int i = 1; i <=15; i++) {
			Connection conn = ds.getConnection();
			System.out.println("第"+i+"个:" + conn);
			
			//如果这里没有关闭,就相当于没有还
//			conn.close();#这里关闭,是还回池中
		}
	}
}

 4. Druid connection pool parameter description

configuration default illustrate
name The significance of configuring this property is that if there are multiple data sources, they can be distinguished by name during monitoring. If not configured, a name will be generated in the format: "DataSource-" + System.identityHashCode(this)
url The url to connect to the database is different for different databases. For example: mysql: jdbc:mysql://10.20.153.104:3306/druid2 oracle: jdbc:oracle:thin:@10.20.149.85:1521:ocnauto
username The username to connect to the database
password Password to connect to the database. If you don't want the password to be written directly in the configuration file, you can use ConfigFilter. See here for details: Using ConfigFilter · alibaba/druid Wiki · GitHub
driverClassName Automatic identification based on url This item can be configured or not. If you do not configure druid, it will automatically identify the jdbType according to the url, and then select the corresponding driverClassName (recommended configuration)
initialSize 0 The number of physical connections established during initialization. Initialization occurs when the init method is called explicitly, or when getConnection is first
maxActive 8 Maximum number of connection pools
maxIdle 8 It is no longer used, and the configuration has no effect
minIdle 0 Minimum number of connection pools
maxWait -1 The maximum waiting time when obtaining a connection, in milliseconds. After maxWait is configured, the fair lock is enabled by default, and the concurrency efficiency will decrease. If necessary, you can use the unfair lock by configuring the useUnfairLock attribute to true.
poolPreparedStatements false Whether to cache preparedStatement, that is, PSCache. PSCache greatly improves the performance of databases that support cursors, such as oracle. It is recommended to close it under mysql.
maxOpenPreparedStatements -1 To enable PSCache, it must be configured to be greater than 0. When it is greater than 0, poolPreparedStatements will be automatically triggered and changed to true. In Druid, there will be no problem of PSCache occupying too much memory under Oracle. You can configure this value to be larger, for example, 100
validationQuery The sql used to check whether the connection is valid requires a query statement. If validationQuery is null, testOnBorrow, testOnReturn, and testWhileIdle will not work.
testOnBorrow true When applying for a connection, execute validationQuery to check whether the connection is valid. Doing this configuration will reduce performance.
testOnReturn false Execute validationQuery to check whether the connection is valid when returning the connection. Doing this configuration will reduce performance
testWhileIdle false It is recommended to configure it as true, which will not affect performance and ensure security. Check when applying for a connection. If the idle time is greater than timeBetweenEvictionRunsMillis, execute validationQuery to check whether the connection is valid.
timeBetweenEvictionRunsMillis There are two meanings: 1) The Destroy thread will detect the connection interval 2) The judgment basis of testWhileIdle, see the description of the testWhileIdle attribute for details
numTestsPerEvictionRun No longer used, a DruidDataSource only supports one EvictionRun
minEvictableIdleTimeMills Configure the minimum survival time of a connection in the pool, in milliseconds
connectionInitSqls The sql executed when the physical connection is initialized
exceptionSorter Automatic identification based on dbType Abandon the connection when the database throws some unrecoverable exception
filters The attribute type is a string, and the extension plug-in is configured through an alias. Commonly used plug-ins include: filter for monitoring statistics: filter for stat logs: log4j filter for preventing SQL injection: wall
proxyFilters The type is List. If filters and proxyFilters are configured at the same time, it is a combination relationship, not a replacement relationship

5. DBUtils _

commons-dbutils is an open source JDBC tool class library provided by the Apache organization. It is a simple encapsulation of JDBC, and the learning cost is extremely low. Using dbutils can greatly simplify the workload of jdbc coding without affecting the performance of the program.

Among them, the QueryRunner class encapsulates the execution of SQL and is thread-safe.

(1) It can add, delete, modify, check, batch process,

(2) Considering that transaction processing needs to share Connection.

(3) The most important thing about this class is to simplify the SQL query. It can be used in combination with ResultSetHandler to complete most of the database operations, which can greatly reduce the amount of coding.

(4) If the connection obtained from the connection pool does not need to be closed manually, the runner will automatically close the connection and release it to the connection pool

Constructor:

Constructor with empty parameters. When performing an operation, the parameter Connection object needs to be passed in. Resources need to be released manually after use.

public QueryRunner() {}

有参构造器,传入一个数据源,执行操作时,从数据源中获取连接,使用完毕自动释放资源。

public QueryRunner(DataSource ds) {}

增删改查操作:

(1)更新

public int update(Connection conn, String sql, Object... params) throws SQLException:用来执行一个更新(插入、更新或删除)操作。

......

(2)插入

public <T> T insert(Connection conn,String sql,ResultSetHandler<T> rsh, Object... params) throws SQLException:只支持INSERT语句,其中 rsh - The handler used to create the result object from the ResultSet of auto-generated keys. 返回值: An object generated by the handler.即自动生成的键值

....

(3)批处理

public int[] batch(Connection conn,String sql,Object params)throws SQLException: INSERT, UPDATE, or DELETE语句

public <T> T insertBatch(Connection conn,String sql,ResultSetHandler<T> rsh,Object params)throws SQLException:只支持INSERT语句

.....

(4)使用QueryRunner类实现查询

public <T> T query(String sql, ResultSetHandler<T> rsh, Object... params) throws SQLException {
}

执行一个查询操作,在这个查询中,对象数组中的每个元素值被用来作为查询语句的置换参数。该方法会自行处理 PreparedStatement 和 ResultSet 的创建和关闭。

public Object query(Connection conn, String sql, ResultSetHandler rsh,Object... params) throws SQLException

执行一个查询操作,在这个查询中,对象数组中的每个元素值被用来作为查询语句的置换参数。

...

ResultSetHandler接口用于处理 java.sql.ResultSet,将数据按要求转换为另一种形式。ResultSetHandler 接口提供了一个单独的方法:Object handle (java.sql.ResultSet rs)该方法的返回值将作为QueryRunner类的query()方法的返回值。

该接口有如下实现类可以使用:

  • BeanHandler:将结果集中的第一行数据封装到一个对应的JavaBean实例中。

  • BeanListHandler:将结果集中的每一行数据都封装到一个对应的JavaBean实例中,存放到List里。

  • ScalarHandler:查询单个值对象

  • MapHandler:将结果集中的第一行数据封装到一个Map里,key是列名,value就是对应的值。

  • MapListHandler:将结果集中的每一行数据都封装到一个Map里,然后再存放到List

  • ColumnListHandler:将结果集中某一列的数据存放到List中。

  • KeyedHandler(name): Encapsulate each row of data in the result set into a Map, and then store these maps in a map, whose key is the specified key.

  • ArrayHandler: Convert the first row of data in the result set into an object array.

  • ArrayListHandler: Convert each row of data in the result set into an array, and then store it in the List.

Guess you like

Origin blog.csdn.net/rbx508780/article/details/127288319