Database connection pool DataSource


What is database connection pool

Database connections are a critical, limited and expensive resource , especially in multi-user web applications. The management of database connections can significantly affect the scalability and robustness of the entire application, and affect the performance indicators of the program. The database connection pool is proposed for this problem. The database connection pool is responsible for allocating, managing, and releasing database connections. It allows applications to reuse an existing database connection instead of re-establishing one; release database connections whose idle time exceeds the maximum idle time to avoid failures due to failure to release database connections. Caused by missing database connections. This technique can significantly improve the performance of database operations.

The following is a comparison legend with and without connection pooling



Advantages of connection pooling

Save the performance consumption of creating and releasing connections

Connections in the connection pool play a role in multiplexing , providing program performance

In fact, when using connection pooling, there are some disadvantages:

The connection pool object must be loaded at the very beginning of the program, so it will definitely consume more resources, but it is also stronger than creating a connection every time.

The principle of connection pool

The basic idea of ​​the connection pool is to store the database connection as an object in memory when the system is initialized. When the user needs to access the database, instead of establishing a new connection, an established idle connection object is taken out from the connection pool. . After use, the user does not close the connection, but puts the connection back into the connection pool for the next request to access. The establishment and disconnection of connections are managed by the connection pool itself. At the same time, you can also control the initial number of connections in the connection pool, the upper and lower limits of the connection, the maximum number of times each connection is used, the maximum idle time, etc. by setting the parameters of the connection pool. It can also monitor the number of database connections, usage, etc. through its own management mechanism.

In layman's terms: get a collection, throw a few connection objects into the collection (connection pool), when the user needs to obtain a connection, take one out of the collection (connection pool), and put it back into the collection after use ( connection pool) for the next reuse, that is, the objects in the connection pool can be reused.


After understanding the source code of the connection pool implementation, I tried to simulate the general implementation principle of writing a simple version of the connection pool.

public class MyDataSource {

	private LinkedList<Connection> ll;

	public MyDataSource() throws SQLException {
		ll = new LinkedList<Connection>();
		//When MyDataSource is created, 10 Connection objects are added to the collection.
		for (int i = 0; i < 10; i++) {
//Use your own encapsulated JdbcUtils tool class to get a connection object
			ll.add(JdbcUtils.getConnection());
		}
	}

	// Get the connection and return the connection in the collection to a
	public Connection getConnection() {
		return ll.removeLast();
	}
	// Close the connection and put the connection object back into the collection
	public void closeConnection(Connection con) {
		ll.addFirst(con);
	}
}
The following is to use the database connection pool created by myself above

public class DataSourceDemo1 {
 
public static void main(String[] args) throws SQLException {
String sql = "select * from account";
// create a connection pool
MyDataSource mds = new MyDataSource();
// Get a connection object from the connection pool
Connection con = mds.getConnection();
 
ResultSet rs = con.prepareStatement(sql).executeQuery();
 
while (rs.next()) {
System.out.println(rs.getInt("id") + "  "
+ rs.getString("username") + "  " + rs.getString("money"));
}
 
rs.close();
//mds.closeConnection(con);//将连接对象重新放回到池中。
con.close();
}
}

连接池规定

javax.sql包下有一个 DataSource

所有的支持java的连接池都应该实现javax.sql.DataSource接口,在这个接口中提供了一个方法  getConnection()它就是获取一个连接对象的。

 

如果连接对象Connection是通过连接池获取的,当通过Connection对象调用close()方法时,不是销毁连接对象,而是将连接对象放回到连接池。所以Connection对象调用close()方法时,具体做什么操作需要看这个Connection对象是怎么来的。

1,如果就是普通获取(驱动管理器DriverManager),那么close()就是关闭连接。

2,如果是通过连接池(DataSource)获取,那么close()就是将连接对象重新放回连接池中。

具体实现方式是使用了动态代理在实现了DataSource接口后对父类Connection的方法进行了重写。


毕竟在开发中,数据库连接池不会让我们去实现,了解了数据库连接池的大概原理后,让我们来看看常用的数据库连接池有哪些以及在开发如何使用。

连接池的使用在项目中一般可以分为两种,一种是直接在java代码中以编码的方式实现,另一种则是通过加载配置文件的方式。

Dbcp连接池(了解)


DBCP Apache 软件基金组织下的开源连接池实现,使用DBCP数据源,应用程序应在系统中增加如下两个 jar 文件:

Commons-dbcp.jar:连接池的实现

Commons-pool.jar:连接池实现的依赖库

Tomcat 的连接池正是采用该连接池来实现的。该数据库连接池既可以与应用服务器整合使用,也可由应用程序独立使用。DBCP Apache 软件基金组织下的开源连接池实现,使用DBCP数据源,应用程序应在系统中增加如下两个 jar 文件:

Commons-dbcp.jar:连接池的实现

Commons-pool.jar:连接池实现的依赖库

Tomcat 的连接池正是采用该连接池来实现的。该数据库连接池既可以与应用服务器整合使用,也可由应用程序独立使用。


dbcp连接池编码实现

// 1.创建连接池对象
BasicDataSource ds = new BasicDataSource();
// 2.设置相关属性
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql:///day13");
ds.setUsername("root");
ds.setPassword("abc");

dbcp连接池配置文件实现
//1.加载配置信息
Properties props = new Properties();//创建了一个map集合					
props.load(new FileInputStream(properties配置文件路径);
		
properties文件内容
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///数据库名
username=root
password=root

// 2.通过BasicDataSourceFactory获取一个连接池对象
DataSource ds = BasicDataSourceFactory.createDataSource(props);


C3p0连接池


C3P0是一个开源的JDBC连接池,它实现了数据源和JNDI绑定,支持JDBC3规范和JDBC2的标准扩展。目前使用它的开源项目有HibernateSpring等。

c3p0dbcp区别

dbcp没有自动回收空闲连接的功能

c3p0有自动回收空闲连接功能

在使用c3p0连接池时将c3p0jar 复制WEB-INF/lib下,我们使用的版本

c3p0-0.9.1.2.jar


c3p0连接池编码实现

ComboPooledDataSource ds = new ComboPooledDataSource();
// 2.手动配置参数
ds.setDriverClass("com.mysql.jdbc.Driver");
ds.setJdbcUrl("jdbc:mysql:///day13");
ds.setUser("root");
ds.setPassword("abc");


c3p0连接池配置文件实现

如果配置文件名称是  c3p0.propertiesc3p0-config.xml

那么c3p0就会默认在classpath根目录下查找这个配置文件。

只要在src下创建c3p0.properties or c3p0-config.xml名称的配置文件,c3p0会自动查找.
ComboPooledDataSource ds = new ComboPooledDataSource();
自动查找配置文件
在src/c3p0-config.xml
<c3p0-config>
	<default-config>
		<property name="driverClass">com.mysql.jdbc.Driver</property>
		<property name="jdbcUrl">jdbc:mysql:///数据库名</property>
		<property name="user">root</property>
		<property name="password">abc</property>
	</default-config>
</c3p0-config>

Connection pool tool class

public class DataSourceUtils {

	private static ComboPooledDataSource cpds = new ComboPooledDataSource();//Automatically load the c3p0-config.xml configuration file to read database connection related information
	//Get the connection object and return a connection object from the connection pool
	public static Connection getConnection() throws SQLException {
		return cpds.getConnection();
		
	}
	//Get the connection pool object
	public static DataSource getDataSource() {
		return cpds;
	}

}







Guess you like

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