百威 发表于 2013-1-25 22:22:54

用java实现数据库连接池的一个简单示例

转载:http://hi.baidu.com/triceratops/blog
import java.util.Stack;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import org.apache.log4j.*;public final class DBConnectionPool {private static DBConnectionPool dbConnectionPool = null;private static int accumulator = 0;private static Logger log = Logger.getLogger(DBConnectionPool.class);private static final int POOL_INIT_SIZE = 128;private static final int POOL_MAX_SIZE = 512;private Stack pool;private String driverName = "com.ibm.db2.jcc.DB2Driver";private String url = "jdbc:db2://192.168.1.100:60000/flamingo";private String user = "daniel";private String password = "850306";public static DBConnectionPool getInstance() throws Exception{   if(dbConnectionPool == null){    synchronized(DBConnectionPool.class){   if(dbConnectionPool == null)      dbConnectionPool = new DBConnectionPool();    }   }   return dbConnectionPool;}private DBConnectionPool() throws ClassNotFoundException, SQLException{   log.setLevel(Level.DEBUG);   pool = new Stack();   initializePool();}private void initializePool() throws ClassNotFoundException, SQLException{   log.info("Database connection pool initializing...");   Connection conn = null;   try{    Class.forName(driverName);    for(int i = 0;i < POOL_INIT_SIZE;i++){   conn = new DBConnection(DriverManager.getConnection       (url,user,password),this).getConnection();       pool.push(conn);       accumulator++;    }   }   catch(ClassNotFoundException e){    log.error("Failure: Cannot find the db2 driver!");    throw e;   }   catch(SQLException e){    log.error("Failure: Cannot connect to the database!");    throw e;   }   log.info("Database connection pool initialized successfully!");   log.info("pool size is: "+pool.size());}public synchronized Connection getConnection() throws ClassNotFoundException, SQLException{   Connection conn;   while(true){      if(!pool.isEmpty()){      conn = (Connection)pool.pop();      if(conn == null || conn.isClosed()){         accumulator--;         continue;      }      return conn;      }      else{      if(accumulator == POOL_MAX_SIZE){         try{          wait(5000);          }         catch(InterruptedException e){          e.printStackTrace();         }      }      else{         //create a new database connection         try{          Class.forName(driverName);          conn = new DBConnection(DriverManager.getConnection       (url,"db2inst2","db2inst2"),this).getConnection();          accumulator++;          return conn;         }         catch(ClassNotFoundException e){          log.error("Failure: Cannot find the db2 driver!");          throw e;         }         catch(SQLException e){          log.error("Failure: Cannot connect to the database!");          throw e;         }      }      }   }}public synchronized boolean returnConnection(Connection conn){   if(pool.size() < POOL_MAX_SIZE){      pool.push(conn);      log.info(conn +" has been returned!");      notify();      return true;   }   return false; // The connection pool is full filled.}public static void main(String[] args) throws Exception{   Connection conn = getInstance().getConnection();   System.out.println(conn);   conn.close();}}===============================================================================import java.sql.Connection;import java.sql.SQLException;import java.lang.reflect.Proxy;import java.lang.reflect.InvocationHandler;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import org.apache.log4j.Logger;import org.apache.log4j.Level;public class DBConnection implements InvocationHandler{private Connection conn;private DBConnectionPool dbConnectionPool;private static Logger log = Logger.getLogger(DBConnectionPool.class);DBConnection(Connection conn,DBConnectionPool dbConnectionPool){   this.conn = conn;   this.dbConnectionPool = dbConnectionPool;   log.setLevel(Level.DEBUG);}//return the proxy of an inner hold connectionConnection getConnection(){   return (Connection)Proxy.newProxyInstance(    conn.getClass().getClassLoader(),new Class[]{Connection.class},this);}public Object invoke(Object proxy,Method method, Object[] args)   throws SQLException, IllegalAccessException,InvocationTargetException{   Object result = null;   try{      log.debug("Method: "+method.getName()+" starts......");      if(method.getName().equals("close")){      close();      }      else{      result = method.invoke(conn,args);      }      log.debug("Method: "+method.getName()+" ends......");   }   catch(SQLException e){      log.error("Database operation failed, please try later...");      throw e;   }   catch(IllegalAccessException e){    log.error(method.getName()+" operation forbidden!");      throw e;   }   catch(InvocationTargetException e){    log.error(method.getName()+" operation forbidden!");      throw e;   }   return result;}private void close() throws SQLException{   if(!dbConnectionPool.returnConnection(getConnection())){    conn.close();    log.info(conn + " is closed!");    conn = null;   }}}
页: [1]
查看完整版本: 用java实现数据库连接池的一个简单示例