`
timesongjie
  • 浏览: 16491 次
  • 性别: Icon_minigender_1
  • 来自: 湖南
社区版块
存档分类
最新评论

jdbcpool

    博客分类:
  • java
阅读更多
下面是java写的数据库连接池代码,可以连接oracle和mysql,当然使用时必须加上对应的驱动包。
public class JdbcPool {

private static List<Connection> pool=new LinkedList<Connection>();
    private static int minConn=10;
    private static int maxConn=50;
    private static int curActive=0;
    private static JdbcPool jp;
    public static JdbcPool getInstance(){
    if(jp==null){
    jp=new JdbcPool();
    }
    return jp;
    }
    private JdbcPool(){
    initPool();
    }
    public void initPool(){
    for(int i=0;i<minConn;i++){
    try {
pool.add(createConnection());
} catch (Exception e) {
e.printStackTrace();
}
    }
    }
private  Connection createConnection() throws Exception{
   String clazz="org.gjt.mm.mysql.Driver";//"oracle.jdbc.driver.OracleDriver";
   String url="jdbc:mysql://localhost:3306/user";//"jdbc:oracle:thin:@127.0.0.1:1521:ORAC";
   String username="root";//"scott";
   String password="root";//"tiger";
   Connection conn=null;
  
   Class.forName(clazz);
   conn=DriverManager.getConnection(url,username,password);
   //保证连接池中存放的是对象代理 Proxy得到动态代理对象
   conn=(Connection)Proxy.newProxyInstance(Connection.class.getClassLoader(),
new Class[]{Connection.class},
new DynamicProxyHandler(conn));
   return conn;
}
public synchronized Connection getConnection() throws Exception{
Connection conn=null;
synchronized (pool) {
if(pool.size()<=0){
if(curActive<=maxConn){
conn=createConnection();//这个已经是代理类
curActive++;
}else{
Thread.sleep(50);
}
}else{
conn=pool.remove(0);
curActive++;
}
}
return conn;
}
private class DynamicProxyHandler implements InvocationHandler{//逻辑处理器
        private Connection conn;
        private DynamicProxyHandler(Connection conn){
        this.conn=conn;
        }
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
if(method.getName()=="close"){
synchronized(pool){
if(pool.size()>minConn){
try {
conn.close();
System.out.println("真正关闭");
} catch (SQLException e) {
e.printStackTrace();
}
}else{
System.out.println(conn.getClass());
conn=(Connection)Proxy.newProxyInstance(Connection.class.getClassLoader(),
new Class[]{Connection.class},
new DynamicProxyHandler(conn));
System.out.println(conn.getClass());
pool.add(conn);
}
}
curActive--;
return null;
}
return method.invoke(conn,args);
}

}
public static void main(String[] args) {
try {
   Connection conn=null;
   for(int i=0;i<100;i++){
   conn=JdbcPool.getInstance().getConnection();
System.out.println(conn.getClass());
conn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics