概述
此文章属于个人看过底层源码以后、自己手写实现的学习文章、如有不对或者考虑的不够具体的方面、请多指教、相互学习、谢谢
package cn.tedu.pool;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;
import javax.sql.DataSource;
/**
* 手写连接池
* @author 16
*
*/
public class MyPool implements DataSource{
//定义一个能够存储连接的数据结构,由于经常使用插入和删除操作,所以List较好。
private static List<Connection> pool = new LinkedList<Connection>();
static{//在程序之后立刻创建一批连接以备使用
try{
Class.forName("com.mysql.jdbc.Driver");
for(int i=0;i<5;i++){
//每次都创建一个新的连接对象
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydemo?user=root&password=root");
//将创建好的每一个连接对象添加到List中,模拟将连接加入连接池
pool.add(conn);
}
}catch(Exception e){
e.printStackTrace();
throw new RuntimeException(e);
}
}
//创建连接(从连接池中取出一个连接)
@Override
public Connection getConnection() throws SQLException {
if(pool.size()==0){//取出连接之前首先判断当前连接池中是否还有连接,如果没有则重新创建一批连接
for(int i=0;i<5;i++){
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydemo?user=root&password=root");
pool.add(conn);
}
}
//从List中取出一个连接对象
//此处不能使用get(),get()方法只能读取对应下标的元素,没有将读取到的元素移除,如果是取出连接对象,应将对象移除。
Connection conn = pool.remove(0);
//注:集合中的.remove() 移除这个值并返回
ConnDecorate connpool = new ConnDecorate(conn,this);
System.out.println("成功获取一个连接,池中还剩:"+pool.size()+"个连接");
return connpool;
}
//返还连接
//手写一个返还连接的方法
public void retConn(Connection conn){
try {
//归还的连接如果没有关闭或者为空,则不允许放入池中。
if(conn!=null&&!conn.isClosed()){
pool.add(conn);
System.out.println("成功还回一个连接,池中还剩:"+pool.size()+"个连接");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public PrintWriter getLogWriter() throws SQLException {
return null;
}
@Override
public void setLogWriter(PrintWriter out) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setLoginTimeout(int seconds) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public int getLoginTimeout() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public Connection getConnection(String username, String password)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
}