DBConnectionManager

package zpxx;
import java.io.*;
import java.sql.*;
import java.util.*;
import java.util.Date;

//建立DBConnectionManager
public class DBConnectionManager
{
 static private DBConnectionManager instance;
 static private int clients;

 private Vector drivers=new Vector();
 private PrintWriter log;
 private Hashtable pools=new Hashtable();

 //返回唯一的實列
 static synchronized public DBConnectionManager getInstance()
 {
  if(instance==null)
  {
   instance=new DBConnectionManager();
  }
  clients++;
  return instance;
 }

 //構造函數!
 private DBConnectionManager()
 {
  init();
 }
 //結束構造函數
 //釋放一個連接
 public void freeConnection(String name,Connection con)
 {
  DBConnectionPool pool=(DBConnectionPool)pools.get(name);
  if(pool!=null)
  {
   pool.freeConnection(con);
  }
 } 
 //結束釋放一個連接

 //取得一個連接
 public Connection getConnection(String name)
 {
  DBConnectionPool pool=(DBConnectionPool)pools.get(name);
  if(pool!=null)
  {
   return pool.getConnection();
  }
  return null;
 }

 public Connection getConnection(String name,String customer)
 {
  DBConnectionPool pool=(DBConnectionPool)pools.get(name);
  if(pool!=null)
  {
   return pool.getConnection(customer);
  }
  return null;
 }

 public Connection getConnection(String name,long time)
 {
  DBConnectionPool pool=(DBConnectionPool)pools.get(name);
  if(pool!=null)
  {
   return pool.getConnection(time);
  }
  return null;
 }
 //結束getconnection
 //關閉所有連接
 public synchronized void release()
 {
//  if(--clients!=0)
//   return;

  Enumeration allPools=pools.elements();
  while(allPools.hasMoreElements())
  {
   DBConnectionPool pool=(DBConnectionPool)allPools.nextElement();
   pool.release();
  }
  Enumeration allDrivers=drivers.elements();
  while(allDrivers.hasMoreElements())
  {
   Driver driver=(Driver)allDrivers.nextElement();
   try
   {
    DriverManager.deregisterDriver(driver);
    log("撤消JDBC驅動程序"+driver.getClass().getName());
   }
   catch(SQLException e)
   {
    log(e,"無法撤消JDBC驅動程序的註冊"+driver.getClass().getName());
   }
  }
 }

 public synchronized void release(String customer)
 {
//  if(--clients!=0)
//   return;

  Enumeration allPools=pools.elements();
  while(allPools.hasMoreElements())
  {
   DBConnectionPool pool=(DBConnectionPool)allPools.nextElement();
   pool.release(customer);
  }
  Enumeration allDrivers=drivers.elements();
  while(allDrivers.hasMoreElements())
  {
   Driver driver=(Driver)allDrivers.nextElement();
   try
   {
    DriverManager.deregisterDriver(driver);
    log(customer+"撤消JDBC驅動程序"+driver.getClass().getName());
   }
   catch(SQLException e)
   {
    log(e,"無法撤消JDBC驅動程序的註冊"+driver.getClass().getName());
   }
  }
 }
 private void createPools(Properties props)
 {
  Enumeration propNames=props.propertyNames();
  while(propNames.hasMoreElements())
  {
   String name=(String) propNames.nextElement();
   if(name.endsWith(".url"))
   {
    String poolName=name.substring(0,name.lastIndexOf("."));
    String url=props.getProperty(poolName+".url");
    if(url==null)
    {
     log("沒有連接池"+poolName+"指定的URL");
     continue;
    }
    String user=props.getProperty(poolName+".user");
    String password=props.getProperty(poolName+".password");
    String maxconn= props.getProperty(poolName+".maxconn","0");
    int max;
    try
    {
     max=Integer.valueOf(maxconn).intValue();
    }
    catch(NumberFormatException e)
    {
     log("錯誤的最大連接數:"+maxconn+".連接池"+poolName);
     max=0;
    }
    DBConnectionPool pool=new DBConnectionPool(poolName,url,user,password,max);
    pools.put(poolName,pool);
    log("成功創建連接池"+poolName);
   }
  }
 }

 private void init()
 {
  InputStream is=getClass().getResourceAsStream("db.properties");
  Properties dbProps=new Properties();
  try
  {
   dbProps.load(is);
  }
  catch(Exception e)
  {
   System.err.println("不能讀取屬性文件。請確保db.properties在你的CLASSPATH中");
   return;
  }
  String logFile=dbProps.getProperty("logfile","DBConnectionManager.log");
  try
  {
   log=new PrintWriter(new FileWriter(logFile,true),true);
  }
  catch(IOException e)
  {
   System.err.println("無法打開日誌文件:"+logFile);
   log=new PrintWriter(System.err);
  }
  loadDriver(dbProps);
  createPools(dbProps);
 }

 private void loadDriver(Properties props)
 {
  String driverClasses=props.getProperty("drivers");
  StringTokenizer st=new StringTokenizer(driverClasses);
  while(st.hasMoreElements())
  {
   String driverClassName=st.nextToken().trim();
   try
   {
    Driver driver=(Driver)Class.forName(driverClassName).newInstance();
    DriverManager.registerDriver(driver);
    drivers.addElement(driver);
    log("成功註冊驅動程序"+driverClassName);
   }
   catch(Exception e)
   {
    log("無法註冊驅動程序:"+driverClassName+",錯誤"+e);
   }
  }
 }

 private void log(String msg)
 {
  log.println(new Date()+":"+msg);
 }
 private void log(Throwable e,String msg)
 {
  log.println(new Date()+":"+msg);
  e.printStackTrace(log);
 }
 class DBConnectionPool
 {
  private int checkOut;
  private Vector freeConnections=new Vector();
  private int maxconn;
  private String name;
  private String password;
  private String URL;
  private String user;

  public DBConnectionPool(String name,String URL,String user,String password,int maxconn)
  {
   this.name=name;
   this.URL=URL;
   this.password=password;
   this.user=user;
   this.maxconn=maxconn;
  }
  public synchronized void freeConnection(Connection con)
  {
   freeConnections.addElement(con);
   checkOut--;
   notifyAll();
  }
  public synchronized Connection getConnection()
  {
   Connection con=null;
   if(freeConnections.size()>0)
   {
    con=(Connection)freeConnections.firstElement();
    freeConnections.removeElementAt(0);
    try
    {
     if(con.isClosed())
     {
      log("從連接池"+name+"刪除一個連接");
      con=getConnection();
     }
    }
    catch(SQLException e)
    {
     log("從連接池"+name+"刪除一個連接");
     con=getConnection();
    }
   }
   else if(maxconn==0||checkOut<maxconn)
   {
    con=newConnection();
   }
   if(con!=null)
   {
    checkOut++;
   }
   return con;
  }

  public synchronized Connection getConnection(String customer)
  {
   Connection con=null;
   if(freeConnections.size()>0)
   {
    con=(Connection)freeConnections.firstElement();
    freeConnections.removeElementAt(0);
    try
    {
     if(con.isClosed())
     {
      log("從連接池"+name+"刪除一個連接");
      con=getConnection();
     }
    }
    catch(SQLException e)
    {
     log("從連接池"+name+"刪除一個連接");
     con=getConnection();
    }
   }
   else if(maxconn==0||checkOut<maxconn)
   {
    con=newConnection(customer);
   }
   if(con!=null)
   {
    checkOut++;
   }
   return con;
  }

  public synchronized Connection getConnection(long timeout)
  {
   long startTime=new Date().getTime();
   Connection con;
   while((con=getConnection())==null)
   {
    try
    {
     wait(timeout);
    }
    catch(InterruptedException e)
    {}
    if((new Date().getTime()-startTime)>=timeout)
    {
     return null;
    }
   }
   return con;
  }
  public void release()
  {
   Enumeration allConnections=freeConnections.elements();
   while(allConnections.hasMoreElements())
   {
    Connection con=(Connection)allConnections.nextElement();
    try
    {
     con.close();
     log("關閉連接池"+name+"中的連接");
    }
    catch(SQLException e)
    {
     log(e,"無法關閉連接池"+name+"中的連接");
    }
   }
   freeConnections.removeAllElements();
  }
  public void release(String customer)
  {
   Enumeration allConnections=freeConnections.elements();
   while(allConnections.hasMoreElements())
   {
    Connection con=(Connection)allConnections.nextElement();
    try
    {
     con.close();
     log(customer+"關閉連接池"+name+"中的連接");
    }
    catch(SQLException e)
    {
     log(e,"無法關閉連接池"+name+"中的連接");
    }
   }
   freeConnections.removeAllElements();
  }
  private Connection newConnection()
  {
   Connection con=null;
   try
   {
    con=DriverManager.getConnection(URL,user,password);
    log("連接池"+name+"創建一個新的連接");
   }
   catch(SQLException e)
   {
    log(e,"無法創建下列URL的連接"+URL);
    return null;
   }
   return con;
  }

  private Connection newConnection(String customer)
  {
   Connection con=null;
   try
   {
    con=DriverManager.getConnection(URL,user,password);
    log(customer+"從連接池"+name+"創建一個新的連接");
   }
   catch(SQLException e)
   {
    log(e,"無法創建下列URL的連接"+URL);
    return null;
   }
   return con;
  }
 }
}

發佈了25 篇原創文章 · 獲贊 0 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章