使用原始的jdbc进行数据库操作,每次操作,我们都需要获得数据库的连接,操作完了之后要释放资源。这样,系统的开销很大。连接池可以帮助我们提高系统的性能。
实际开发中“获得连接”或“释放资源”是非常消耗系统资源的两个过程,为了解决此类性能问题,通常情况我们采用连接池技术,来共享连接Connection.
一、连接池概述
1.1 连接池概念
用池来管理Connection,这样可以重复使用Connection。有了池,所以我们就不用自己来创建Connection,而是通过池来获取Connection对象。当使用完Connection后,调用Connection的close()方法也不会真的关闭Connection,而是把Connection“归还”给池。池就可以再利用这个Connection对象了。
1.2 规范
Java为数据库连接池提供了公共的接口: javax.sql.DataSource,各个厂商需要让自己的连接池实现这个接口。这样应用程序可以方便的切换不同厂商的连接池。
常见的连接池DBCP、C3P0。
二、自定义连接池
2.1 案例分析
如果我们要编写自定义连接池,需要完成以下步骤:
1.创建连接池实现(数据源),并实现接口javax.sql.DataSource。因为我们只使用该接口中getConnection()方法,简化本案例,我们将自己提供方法,而没有实现接口。
2.提供一个集合,用于存放连接,因为移除/添加操作多,所以选择LinkedList
3.本例在静态代码矿中,为连接池初始化3个连接
4.之后程序如果需要连接,调用实现类的getConnection(),本方法将从连接池(容器list)获得连接。为了保证当前连接只能提供给一个线程使用,所以我们需要将连接先从连接池中移除。
5.当用户使用完连接,释放资源时,不执行close()方法,而是将连接添加到连接池中。
MyDataSource:
public class MyDataSource implements DataSource {
// 1.创建1个容器用于存储Connection对象
private static LinkedList<Connection> pool = new LinkedList<>();
// 2.创建5个连接放到容器中去
static {
for (int i = 0; i < 5; i++) {
Connection conn = JDBCUtils_V3.getConnection();
pool.add(conn);
}
}
/**
* 重写获取连接的方法
*
* @return
* @throws SQLException
*/
@Override
public Connection getConnection() throws SQLException {
Connection conn = null;
// 3.使用前先判断
if (pool.size() == 0) {
// 4.池子里面没有,我们再创建一些
for (int i = 0; i < 5; i++) {
conn = JDBCUtils_V3.getConnection();
pool.add(conn);
}
}
// 5.从池子里面获取一个连接对象Conn
conn = pool.remove(0);
return conn;
}
...省略其他方法
}
测试类:
public class TestMyDataSource {
@Test
public void testAddUser() {
Connection conn = null;
PreparedStatement pstmt = null;
// 1.创建自定义连接池对象
MyDataSource dataSource = new MyDataSource();
try {
// 2.从池子中获取连接
conn = dataSource.getConnection();
String sql = "insert into t_customer values(?, ?,?)";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, 1);
pstmt.setString(2, "kenneth");
pstmt.setInt(3, 20);
int rows = pstmt.executeUpdate();
if (rows > 0) {
System.out.println("添加成功");
} else {
System.out.println("添加失败");
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
dataSource.backConnection(conn);
}
}
}
第一个案例的源码
三、C3P0连接池
C3P0开源免费的连接池!目前使用它的开源项目有:Spring、Hibernate等。使用第三方工具需要导入jar包,c3p0使用时还需要添加配置文件c3p0-config.xml。
3.1 导包
c3p0-0.9.1.2.jar
3.2 配置文件
配置文件名称:c3p0-config.xml(固定)
配置文件位置:src(类路径)
配置文件内容:
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql:///hibernate_first</property>
<property name="user">root</property>
<property name="password">123456</property>
<property name="initialPoolSize">5</property>
<property name="maxPoolSize">20</property>
</default-config>
<named-config name="itheima">
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql:///hibernate_first</property>
<property name="user">root</property>
<property name="password">123456</property>
</named-config>
</c3p0-config>
3.3 编写工具类
C3P0提供核心工具类:ComboPooledDataSource,如果要使用连接池,必须创建该类的实例对象。
new ComboPooledDataSource("名称"); 使用配置文件“命名配置”
3.4 使用
public class TestC3P0 {
@Test
public void test() {
Connection conn = null;
PreparedStatement pstmt = null;
// 1.使用c3p0连接池对象
ComboPooledDataSource dataSource = new ComboPooledDataSource();// 加载默认的配置
// ComboPooledDataSource dataSource = new ComboPooledDataSource("itheima");//加载有名称的配置
try {
// 2.从池子中获取连接
conn = dataSource.getConnection();
String sql = "insert into t_customer values(?, ?,?)";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, 2);
pstmt.setString(2, "java");
pstmt.setInt(3, 20);
int rows = pstmt.executeUpdate();
if (rows > 0) {
System.out.println("添加成功");
} else {
System.out.println("添加失败");
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
dataSource.close();
}
}
}