java连接池和代理

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;


import com.sun.org.apache.bcel.internal.generic.NEW;


/*1.mypool.java连接池类
 2.指定全局参数:初始化数目、最大连接数、当前连接、连接池的集合
 3.构造函数:循环创建初始化几个连接
 4.写一个创建连接的方法
 5.获取连接
 池中有连接,直接拿
 池中没有连接
 达到最大连接数据,抛异常
 没到最大连接数,创建
 6.释放连接*/


/*
 * 连接池的操作
 */
public class MyPool {
private static String url = "jdbc:mysql://localhost:3306/day15?characterEncoding=utf8";
private static String user = "root";
private static String password = "root";
private int init_count = 3;
private int max_count = 6;
private int current_count = 0;
// 设置连接池列表
LinkedList<Connection> list = new LinkedList<Connection>();


public MyPool() {
// 循环创建连接
for (int i = 0; i < init_count; i++) {
current_count++;
list.addLast(createConnection());
}
}


private Connection createConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
try {
final Connection conn = DriverManager.getConnection(url, user, password);
//对con创建其代理对象
Connection proxy= (Connection)Proxy.newProxyInstance(
conn.getClass().getClassLoader(), //类加载器
// conn.getClass().getInterfaces(), //目标对象实现的接口
new Class[]{Connection.class},
new InvocationHandler() {  //当调用con对象方法的时候,自动触发事件处理器

@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
//方法返回值
Object result=null;
// 当前执行的方法的方法名
String methodName=method.getName();
if(methodName.equals("close"))
{
System.out.println("begin:当前执行close方法开始");
   list.addLast(conn);
   System.out.println("end:当前连接已经放入连接池");
}
else {
//调用目标对象方法
result=method.invoke(conn, args);
}
return result;
}
});
return proxy;
} catch (SQLException e) {
throw new RuntimeException(e);
}
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}


public Connection getConnection() {
/*
* 5.获取连接 //池中有连接,直接拿 if (list.size()>0) { return list.removeFirst(); }
* /*池中没有连接 达到最大连接数据,抛异常 没到最大连接数,创建
*/
if (current_count < max_count) {
current_count++;
return createConnection();
}


throw new RuntimeException("当前连接数已经达到最大连接数目!");
}


//关闭连接
public void closeConnection(Connection conn) {
if (list.size() < init_count) {
list.addLast(conn);
} else {
try {
conn.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值