动态代理写connection连接池Demo

时间:2022-02-09 15:14:07
 public class JdbcUtil2 {
//声明连接池<放到LinkedList中,操作其中对象的速度快 只需要改变连接>
private static LinkedList<Connection> connectionspool=new LinkedList<Connection>();
//静态代码块
static{
try {
String url="jdbc:mysql://localhost:3306/jdbcdb";
String user="root";
String password="mysql";
Class.forName("com.mysql.jdbc.Driver");
//创建3个连接并将它们代理
for(int i=0;i<3;i++)
{
final Connection conn=DriverManager.getConnection(url, user, password);
//对conn进行代理
Object proxyobj= Proxy.newProxyInstance(
JdbcUtil2.class.getClassLoader(),
new Class[]{Connection.class},
new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
//是否是close方法
if(method.getName().equals("close"))
{
synchronized(connectionspool){
connectionspool.addLast((Connection)proxy);
connectionspool.notify();
}
return null;//如果调用的是close()方法,不会调用代理类的方法,会调用代理
}
return method.invoke(conn, args);
}
}); connectionspool.add((Connection)proxyobj); }
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} public static Connection getConnection()
{
synchronized(connectionspool)
{
if(connectionspool.size()==0)
{
try {
connectionspool.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return getConnection();
}
else {
Connection conn=connectionspool.removeFirst();
System.err.println("pool中还有连接数:"+connectionspool.size());
return conn;
}
}
}
}

利用多线程测试代理连接池

 public class TestProxy  {
public static void main(String[] args) {
for(int i=0;i<3000;i++)
{
new MyThread().start();
}
}
} class MyThread extends Thread
{
@Override
public void run() {
Connection con = null;
try{
con = JdbcUtil2.getConnection();
System.err.println(this.getName()+","+con);
con.setAutoCommit(false);//设置事务的开始
String sql = "insert into users values('"+this.getName()+"','Tom','44')";
Statement st = con.createStatement();
st.execute(sql);
con.commit();
System.err.println(this.getName()+"子线程执行完成。。。。。");
}catch(Exception e){
e.printStackTrace();
}finally{
try {
con.setAutoCommit(true);
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}