【JDBC】数据库连接池技术
1.为什么需要数据库连接池?
我们在讲多线程的时候说过,创建线程是一个昂贵的操作,如果有大量的小任务需要执行,并且频繁地创建和销毁线程,实际上会消耗大量的系统资源,往往创建和消耗线程所耗费的时间比执行任务的时间还长,所以,为了提高效率,可以用线程池。
类似的,在执行JDBC的增删改查的操作时,如果每一次操作都来一次打开连接,操作,关闭连接,那么创建和销毁JDBC连接的开销就太大了。为了避免频繁地创建和销毁JDBC连接,我们可以通过连接池(Connection Pool)复用已经创建好的连接。
JDBC连接池有一个标准的接口javax.sql.DataSource
,注意这个类位于Java标准库中,但仅仅是接口。要使用JDBC连接池,我们必须选择一个JDBC连接池的实现。常用的JDBC连接池有:
- HikariCP
- C3P0
- BoneCP
- Druid(推荐使用!🐀)
示意图:
2.C3P0连接池
C3P0是一个开源的JDBC连接池,它实现了数据源和JNDI绑定,支持JDBC3规范和JDBC2的标准扩展。c3p0是异步操作的,缓慢的JDBC操作通过帮助进程完成。扩展这些操作可以有效的提升性能。目前使用它的开源项目有hibernate,spring等。是一个成熟的、高并发的JDBC连接池库,用于缓存和重用PreparedStatements支持。c3p0具有自动回收空闲连接功能。
🦔
注意:下面这个这是c3p0数据库连接池的辅助包,如果没有这个包系统启动时会报classnotfoundexception
,这是更新c3p0-0.9.2版本后分离出来的包,0.9.1的时候还是只是一个包
mchange-commons-java-0.2.15.jar下载地址
或者更简单的,直接使用Maven导包:
<!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
使用的第一种方式:相关参数在程序中指定:
/**
* 相关参数在程序中指定
*/
@Test
public void test1() throws IOException, PropertyVetoException, SQLException {
// 创建数据库对象
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
Properties properties = new Properties();
properties.load(new FileInputStream("src\\mysql.properties"));
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String url = properties.getProperty("url");
String driver = properties.getProperty("driver");
// 给数据源comboPooledDataSource设置相关参数
comboPooledDataSource.setDriverClass(driver);
comboPooledDataSource.setJdbcUrl(url);
comboPooledDataSource.setUser(user);
comboPooledDataSource.setPassword(password);
// 初始化连接数
comboPooledDataSource.setInitialPoolSize(10);
// 设置最大连接数,其余的将会进入等待队列
comboPooledDataSource.setMaxPoolSize(50);
// 获取连接
Connection connection = comboPooledDataSource.getConnection();
System.out.println("连接成功!");
connection.close();
}
使用的第二种方式:使用配置文件模板来完成连接:
c3p0-config.xml
文件:(文件名不要改)
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<!--数据源名称-->
<named-config name="imustctf">
<!--加载驱动-->
<property name="driverClass">com.mysql.cj.jdbc.Driver</property>
<!--数据库url-->
<property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbc_test?useSSL=false&serverTimezone=GMT%2B8&rewriteBatchedStatements=true</property>
<!--数据库用户名-->
<property name="user">root</property>
<!--数据库密码-->
<property name="password">root</property>
<!--初始的连接数-->
<property name="initialPoolSize">10</property>
<!--最大连接数-->
<property name="maxPoolSize">50</property>
<!--最小连接数-->
<property name="minPoolSize">5</property>
<property name="maxIdleTime">60</property>
<!--可连接的最多命令对象数-->
<property name="maxStatements">50</property>
<!--每次增长的连接数-->
<property name="acquireIncrement">5</property>
<property name="acquireRetryAttempts">5</property>
<property name="acquireRetryDelay">1000</property>
</named-config>
</c3p0-config>
测试代码:
/**
* 使用配置文件模板来完成连接
*/
@Test
public void test2() throws SQLException {
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource("imustctf");
Connection connection = comboPooledDataSource.getConnection();
System.out.println("连接成功!");
connection.close();
}
3.徳鲁伊连接池
Druid连接池是阿里巴巴开源的数据库连接池项目。Druid连接池为监控而生,内置强大的监控功能,监控特性不影响性能。功能强大,能防SQL注入,内置Loging能诊断Hack应用行为。
或者使用Maven:
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.14</version>
</dependency>
druid.properties
文件:(文件名可以改,文件中key值不要改)
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbc_test?useSSL=false&serverTimezone=GMT%2B8&rewriteBatchedStatements=true
username=root
password=root
initialSize=10
minIdle=5
maxActive=20
maxWait=5000
Druid连接池测试连接代码:
Properties properties = new Properties();
properties.load(new FileInputStream("src\\druid.properties"));
// 创建一个指定参数的数据库连接池
DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
Connection connection = dataSource.getConnection();
System.out.println("连接成功!");
connection.close();
4.Druid工具类
工具类:
/**
* DruidJDBC工具类
*/
public class DruidJdbcUtils {
private static DataSource ds = null;
static {
try {
Properties properties = new Properties();
properties.load(new FileInputStream("src\\druid.properties"));
ds = DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 获取数据库连接池连接
*
* @return 一个连接池连接
*/
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
/**
* 关闭连接
* 并不是真的关闭连接,而是把Connection对象放回连接池
*
* @param resultSet 结果集
* @param statement 用于执行sql语句的对象
* @param connection 数据库连接
*/
public static void close(ResultSet resultSet, Statement statement, Connection connection) {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
测试类:
/**
* DruidJdbcUtils测试
*/
public class DruidJdbcUtilsTest {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
String sql = "update user set school = ? where id = ?";
try {
connection = DruidJdbcUtils.getConnection();
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, "北疆大学");
preparedStatement.setInt(2, 50);
preparedStatement.executeUpdate();
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
// 关闭连接
DruidJdbcUtils.close(null, preparedStatement, connection);
}
}
}