自定义数据库连接池

来源:互联网 发布:java实验心得体会 编辑:程序博客网 时间:2024/05/01 08:46

 在使用JDBC操作数据库时,操作数据库:1.先创建一个连接对象2.执行操作 3.操作完毕,再把连接关闭。

 是否影响程序执行的效率?   频繁的的创建,关闭连接。

所以就引入了连接池技术



/**
 * 自定义连接池
 * 
 * 先定义参数信息 1.定义存储连接对象的集合(连接池) 2.定义初始化连接数目:init_count=3 3.最大连接数:max_count=6
 * 4.当前连接数:current_count=0;
 * 
 * 实现步骤: 1.写一个创建连接的方法;createConnection() 2.通过构造函数初始化3个连接 3.定义一个返回连接的方法
 * getConnection() 4.定义释放连接的方法,把连接放回连接池
 */
public class MyPool {


private int init_count = 3;// 初始化连接数目
private int max_count = 6;// 连接数目最大数
private int current_count;// 当前连接数目
// 存放初始化的连接(连接池)
private LinkedList<Connection> pool = new LinkedList<Connection>();


// 1.创建连接
private Connection createConnection() {


try {
// 加载类
Class.forName("com.mysql.jdbc.Driver");
// 获取连接 ;目标源
final Connection conn = DriverManager.getConnection(
"jdbc:mysql:///day21", "root", "6497054");
//给 conn对象创建代理对象,因为要检测一些方法的执行;最后返回代理对象
Connection proxy=(Connection) Proxy.newProxyInstance(this.getClass().getClassLoader(), //类加载器 
new Class[]{ Connection.class},
new InvocationHandler() {

public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
//对close方法增加功能:把连接放入连接池中
//获取方法名:
String methodName=method.getName();
if("close".equals(methodName)){
System.out.println("执行close方法前");
//把连接放入连接池
releaseConnection(conn);
System.out.println("执行close方法完毕,已经把连接放入连接池");
return null;
}else{
return method.invoke(conn, args);//执行目标对象方法
}
}
});
return proxy;


} catch (Exception e) {


throw new RuntimeException(e);
}


}


// 2.通过构造函数初始化连接
public MyPool() {


for (int i = 0; i < init_count; i++) {
// 创建一个连接
Connection conn = createConnection();
// 记录当前连接数
current_count++;
// 添加到连接池中
pool.add(conn);


}


}


// 3.定义一个返回连接的方法:1.从连接池中取;2.当没有到达最大连接数,连接池不够用,就创建连接
public Connection getConnection() {
// 1 先判断连接池中是否有连接,如果有,就直接拿出来连接
if (pool.size() > 0) {


return pool.removeFirst();
}
// 2.如果连接池没有了,当没有达到最大连接数,就创建连接对象
if (current_count < max_count) {
// 记录连接数
current_count++;


return createConnection();


}


// 3.如果有达到最大连接数,就提示报错。


throw new RuntimeException("连接达到最大连接数目");


}


// 4.释放连接
public void releaseConnection(Connection conn) {
// 当连接池中连接数小于初始化连接数目,
if (pool.size() < init_count) {
// 把连接放入连接池
pool.add(conn);
} else {// 直接关闭


try {
if (conn != null) {
conn.close();
//记录当前连接
current_count--;
conn = null;
}


} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
public static void main(String[] args) throws SQLException {
MyPool myPool=new MyPool();
System.out.println(myPool.pool.size());//池中连接数目
System.out.println(myPool.current_count);//当前连接数

Connection conn1=myPool.getConnection();
Connection conn2=myPool.getConnection();
Connection conn3=myPool.getConnection();
Connection conn4=myPool.getConnection();
System.out.println(myPool.pool.size());//池中连接数目
System.out.println(myPool.current_count);//当前连接数
conn1.close();
conn2.close();
conn3.close();
conn4.close();
System.out.println(myPool.pool.size());//池中连接数目
System.out.println(myPool.current_count);//当前连接数
}
}
0 0
原创粉丝点击