/**
* 自定义连接池, 管理连接
* 代码实现:
1. MyPool.java 连接池类,
2. 指定全局参数: 初始化数目、最大连接数、当前连接、 连接池集合
3. 构造函数:循环创建3个连接
4. 写一个创建连接的方法
5. 获取连接
------> 判断: 池中有连接, 直接拿
------> 池中没有连接,
------> 判断,是否达到最大连接数; 达到,抛出异常;没有达到最大连接数,
创建新的连接
6. 释放连接
-------> 连接放回集合中(..)
*
*/
public class MyPool {
private int init_count = 3;
private int max_count = 6;
private int current_count = 0;
private LinkedList<Connection> pool = new LinkedList<Connection>();
public MyPool() {
for (int i=0; i<init_count; i++){
current_count++;
Connection con = createConnection();
pool.addLast(con);
}
}
private Connection createConnection(){
try {
Class.forName("com.mysql.jdbc.Driver");
final Connection con = DriverManager.getConnection("jdbc:mysql:///jdbc_demo", "root", "root");
/**********对con对象代理**************/
Connection proxy = (Connection) Proxy.newProxyInstance(
con.getClass().getClassLoader(),
new Class[]{Connection.class},
new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object result = null;
String methodName = method.getName();
if ("close".equals(methodName)) {
System.out.println("begin:当前执行close方法开始!");
pool.addLast(con);
System.out.println("end: 当前连接已经放入连接池了!");
} else {
result = method.invoke(con, args);
}
return result;
}
}
);
return proxy;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public Connection getConnection(){
if (pool.size() > 0){
return pool.removeFirst();
}
if (current_count < max_count) {
current_count++;
return createConnection();
}
throw new RuntimeException("当前连接已经达到最大连接数目 !");
}
public void realeaseConnection(Connection con) {
if (pool.size() < init_count){
pool.addLast(con);
} else {
try {
current_count--;
con.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
public static void main(String[] args) throws SQLException {
MyPool pool = new MyPool();
System.out.println("当前连接: " + pool.current_count);
pool.getConnection();
pool.getConnection();
Connection con4 = pool.getConnection();
Connection con3 = pool.getConnection();
Connection con2 = pool.getConnection();
Connection con1 = pool.getConnection();
con1.close();
pool.getConnection();
System.out.println("连接池:" + pool.pool.size());
System.out.println("当前连接: " + pool.current_count);
}
}