编写一个简单jdbc连接池,使用Proxy代理类似Spring aop可以在调用Connection的方法前后添加一些判断!
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;
public class JdbcPool2 {
private int init_count=3; //初始化连接池
private int current_count=0; //当前使用连接数
private int max_count=6; //最大连接数
LinkedList<Connection> connList = new LinkedList<Connection>();
public JdbcPool2() {
for(int i=0;i<init_count;i++) {
connList.add(createConn());
}
}
public Connection getConn() {
if(connList.size()>0) {
current_count ++;
System.out.println("从连接池中取出一条...");
return connList.removeFirst();
}
if(current_count<max_count) {
current_count ++;
System.out.println("连接池用完,新建一条连接...");
return createConn();
}
throw new RuntimeException("已达最大连接数!");
}
public void closeConn(Connection conn) {
if(connList.size()<init_count) {
current_count--;
connList.addLast(conn);
}else {
try {
current_count --;
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public Connection createConn() {
try {
Class.forName("com.mysql.jdbc.Driver");
final Connection conn = DriverManager.getConnection(
"url",
"user",
"password");
Connection proxy =(Connection) Proxy.newProxyInstance(
conn.getClass().getClassLoader(),
new Class[] {Connection.class},
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws
Throwable {
Object result = null;
String name = method.getName();
if(name.equals("close")) {
current_count --;
if(connList.size()<init_count) {
//连接池小于初始化 就把连接回收list中
connList.addLast(conn);
System.out.println("回收连接池完毕!");
}else {
//否则就直接关闭连接
conn.close();
System.out.println("连接池已满,连接直接关闭!");
}
}else {
result = method.invoke(conn, args);
}
return result;
}
});
return proxy;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
JdbcPool2 pool = new JdbcPool2();
Connection conn1 = pool.getConn();
Connection conn2 =pool.getConn();
Connection conn3 = pool.getConn();
Connection conn4 = pool.getConn();
Connection conn5 = pool.getConn();
Connection conn6 = pool.getConn();
try {
conn1.close();
conn2.close();
conn3.close();
conn4.close();
conn5.close();
} catch (SQLException e) {
e.printStackTrace();
}
pool.getConn();
pool.getConn();
System.out.println("连接池剩余:"+pool.connList.size());
System.out.println("当前使用:"+pool.current_count);
System.out.println("剩余连接数:"+(pool.max_count-pool.current_count));
}
}
输出:
从连接池中取出一条...
从连接池中取出一条...
从连接池中取出一条...
连接池用完,新建一条连接...
连接池用完,新建一条连接...
连接池用完,新建一条连接...
回收连接池完毕!
回收连接池完毕!
回收连接池完毕!
连接池已满,连接直接关闭!
连接池已满,连接直接关闭!
从连接池中取出一条...
从连接池中取出一条...
连接池剩余:1
当前使用:3
剩余连接数:3