自定义连接池
什么是连接池?
连接池是装有连接的容器,使用连接的话,可以从连接池中进行获取,使用完成之后将连接归还给连接池。
为什么要学习连接池?
连接对象创建和销毁是需要耗费时间的,在服务器初始化的时候就初始化一些连接。把这些连接放入到内存中,使用的时候可以从内存中获取,使用完成之后将连接放入连接池中。从内存中获取和归还的效率要远远高于创建和销毁的效率。(提升性能)。
连接池原理:
自定义连接池的实现步骤:
1.编写一个类实现DataSource接口
2.重写getConnection方法
3.初始化多个连接在内存中
4.编写归还连接的方法
5.自定义连接池的代码实现
代码实现:
在该代码中会用到之前代码文章中JDBC连接数据库工具类提取中的工具类。
/**
* 自定义连接池
* @author jt
*
*/
public class MyDataSource implements DataSource {
// 将一些连接存入到内存中,可以定义一个集合,用于存储连接对象。
private List<Connection> connList = new ArrayList<Connection>();
// 在初始化的时候提供一些连接
public MyDataSource() {
// 初始化连接:
for(int i = 1;i<=3;i++){
// 向集合中存入连接:
connList.add(JDBCUtils.getConnection());
}
}
// 从连接池中获得连接的方法
@Override
public Connection getConnection() throws SQLException {
Connection conn = connList.remove(0);
// 增强连接:
MyConnectionWrapper connWrapper = new MyConnectionWrapper(conn, connList);
return connWrapper;
}
// 编写一个归还连接的方法:
/*public void addBack(Connection conn){
connList.add(conn);
}*/
@Override
public PrintWriter getLogWriter() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public int getLoginTimeout() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
// TODO Auto-generated method stub
return null;
}
@Override
public void setLogWriter(PrintWriter arg0) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setLoginTimeout(int arg0) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public boolean isWrapperFor(Class<?> arg0) throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public <T> T unwrap(Class<T> arg0) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Connection getConnection(String arg0, String arg1) throws SQLException {
// TODO Auto-generated method stub
return null;
}
}
测试代码:
/**
* 自定义连接池的测试类
* @author jt
*
*/
public class DataSourceDemo1 {
@Test
/**
* 测试自定义连接池
*/
public void demo1(){
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
DataSource dataSource = null;
try{
// 获得连接:
// conn = JDBCUtils.getConnection();
// 从连接池中获得连接:
dataSource = new MyDataSource();
conn = dataSource.getConnection();
// 编写SQL:
String sql = "select * from account";
// 预编译SQL:
pstmt = conn.prepareStatement(sql);
// 设置参数:
// 执行SQL:
rs = pstmt.executeQuery();
while(rs.next()){
System.out.println(rs.getInt("id")+" "+rs.getString("name")+" "+rs.getDouble("money"));
}
}catch(Exception e){
e.printStackTrace();
}finally{
//JDBCUtils.release(rs, pstmt, conn);
if(rs != null){
try{
rs.close();
}catch(SQLException e){
e.printStackTrace();
}
}
if(pstmt != null){
try{
pstmt.close();
}catch(SQLException e){
e.printStackTrace();
}
}
// 归还连接:
dataSource.addBack(conn);
}
}
}