且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java数据库连接池实现

更新时间:2022-05-14 21:00:38

至于Java数据库连接池的原理就不细说了,百度一下大把。在这里只是把个人学习中的结果积累下来。

代码上也基本都有注释。

首先写一个读取本地数据库驱动,数据库用户名、数据库密码、连接数的类。


  1. XML/HTML 代码复制内容到剪贴板  
  2.       
  3. package cn.cate.utils;          
  4.           
  5. import java.io.FileNotFoundException;          
  6. import java.io.FileReader;          
  7. import java.io.IOException;          
  8. import java.util.Properties;          
  9.           
  10. public class PoolProperties {          
  11.           
  12.     private Properties properties;          
  13.     private String driver;          
  14.     private String url;          
  15.     private String user;          
  16.     private String password;          
  17.     private int maxConn;          
  18.     private int minConn;          
  19.               
  20.     public PoolProperties(){          
  21.         properties = new Properties();          
  22.         String path = getClass().getProtectionDomain().getCodeSource().getLocation().toString();          
  23.         pathpathpath = path.substring(6, path.length());          
  24.         if (path.indexOf("WEB-INF") > 0) {          
  25.               pathpathpath = path.substring(0, path.indexOf("/WEB-INF") + 9) + "lib/";          
  26.         }else{          
  27.               path = "d:";          
  28.         }          
  29.         try {          
  30.             this.properties.load(new FileReader(path + "db.pro"));          
  31.         }catch (FileNotFoundException e) {          
  32.             e.printStackTrace();          
  33.         }catch (IOException e) {          
  34.             e.printStackTrace();          
  35.         }          
  36.         this.setDriver(properties.getProperty("driver"));          
  37.         this.setUrl(properties.getProperty("url"));          
  38.         this.setUser(properties.getProperty("user"));          
  39.         this.setPassword(properties.getProperty("password"));          
  40.         this.setMaxConn(Integer.parseInt(properties.getProperty("maxConn")));          
  41.         this.setMinConn(Integer.parseInt(properties.getProperty("minConn")));          
  42.     }          
  43.               
  44.               
  45.     public Properties getProperties() {          
  46.         return properties;          
  47.     }          
  48.           
  49.     public void setProperties(Properties properties) {          
  50.         this.properties = properties;          
  51.     }          
  52.           
  53.     public String getDriver() {          
  54.         return driver;          
  55.     }          
  56.           
  57.     public void setDriver(String driver) {          
  58.         this.driver = driver;          
  59.     }          
  60.           
  61.     public String getUrl() {          
  62.         return url;          
  63.     }          
  64.           
  65.     public void setUrl(String url) {          
  66.         this.url = url;          
  67.     }          
  68.           
  69.     public String getUser() {          
  70.         return user;          
  71.     }          
  72.           
  73.     public void setUser(String user) {          
  74.         this.user = user;          
  75.     }          
  76.           
  77.     public String getPassword() {          
  78.         return password;          
  79.     }          
  80.           
  81.     public void setPassword(String password) {          
  82.         this.password = password;          
  83.     }          
  84.           
  85.     public int getMaxConn() {          
  86.         return maxConn;          
  87.     }          
  88.           
  89.     public void setMaxConn(int maxConn) {          
  90.         this.maxConn = maxConn;          
  91.     }          
  92.           
  93.     public int getMinConn() {          
  94.         return minConn;          
  95.     }          
  96.           
  97.     public void setMinConn(int minConn) {          
  98.         this.minConn = minConn;          
  99.     }          
  100.               
  101.               
  102. }      

db.pro的内容如下:

  driver=com.mysql.jdbc.Driver         maxConn=10           minConn=1           url=jdbc:mysql://127.0.0.1:3306/cate           user=root           password=11111

然后定义一个数据库连接池:DBConnectionPool

 


  1. Java 代码复制内容到剪贴板  
  2.       
  3. import java.sql.Connection;          
  4. import java.sql.DriverManager;          
  5. import java.sql.SQLException;          
  6. import java.util.ArrayList;          
  7. import java.util.Iterator;          
  8. import java.util.List;          
  9.           
  10. /*       
  11. * 此内部类定义了一个连接池,它能够根据要求创建连接,直到预定的最大连接数为止。       
  12. * 在返回连接给客户程序之前,它能够验证连接的有效性。       
  13. */          
  14. public class DBConnectionPool {          
  15.           
  16.     /*       
  17.      * 连接池       
  18.      */          
  19.     private List<Connection> freeConnections = new ArrayList<Connection>();          
  20.     private Connection conn = null;          
  21.     private int connect = 0;     //使用的连接数          
  22.     private int maxConn;      //最大连接数          
  23.     private String driver;    //数据库驱动          
  24.     private String url;     //数据库连接地址          
  25.     private String user;     //用户名          
  26.     private String password;      //用户名          
  27.               
  28.     public DBConnectionPool(String driver,String URL,String user,String password,int maxConn){          
  29.         this.driver = driver;          
  30.         this.url = URL;          
  31.         this.user = user;          
  32.         this.password = password;          
  33.         this.maxConn = maxConn;          
  34.         poolInfo();          
  35.     }          
  36.               
  37.     /*       
  38.      * 显示准备创建连接池的信息       
  39.      */          
  40.     private void poolInfo(){          
  41.         Connection conn = this.newConnection();          
  42.         freeConnections.add(conn);          
  43.         for(int i = 0;i < this.maxConn - 1;i++){          
  44.             Connection freeConn = conn;          
  45.             freeConnections.add(freeConn);          
  46.         }          
  47.     }          
  48.               
  49.     /*       
  50.      * 用完,释放一个连接       
  51.      */          
  52.     public synchronized void freeConnection(Connection conn){          
  53.         this.freeConnections.add(conn);          
  54.         this.connect--;          
  55.     }          
  56.               
  57.     /*       
  58.      * 从连接池中获取一个可用连接,当无法从连接池中获取可用连接时,新创建一个连接       
  59.      */          
  60.     public synchronized Connection getConnection(){          
  61.         if(this.freeConnections.size() > 0){          
  62.             /*       
  63.              * 当在连接池中取出一个连接后,删除此连接       
  64.              */          
  65.             conn = this.freeConnections.get(0);          
  66.             this.freeConnections.remove(0);          
  67.         }          
  68.         /*       
  69.          * 当取出的连接为null时,递归调用自己,直到获得一个可用连接为止       
  70.          */          
  71.         if(conn == null){          
  72.             conn = getConnection();          
  73.         }else{          
  74.             conn = newConnection();          
  75.         }          
  76.         if(this.maxConn == 0 || this.maxConn < this.connect){          
  77.             /*       
  78.              * 等待超过最大连接时       
  79.              */          
  80.             conn = null;          
  81.         }          
  82.         if(conn != null){          
  83.             this.connect++;          
  84.         }          
  85.         return conn;          
  86.     }          
  87.               
  88.     /*       
  89.      * 释放全部连接       
  90.      */          
  91.     public synchronized void release(){          
  92.         Iterator<Connection> allConns = this.freeConnections.iterator();          
  93.         while(allConns.hasNext()){          
  94.             Connection conn = (Connection)allConns.next();          
  95.             try{          
  96.                 if(null != conn){          
  97.                     conn.close();          
  98.                 }          
  99.                 conn = null;          
  100.             }catch(SQLException e){          
  101.                 e.printStackTrace();          
  102.             }          
  103.         }          
  104.         this.freeConnections.clear();          
  105.     }          
  106.               
  107.     /*       
  108.      * 创建一个数据库连接对象       
  109.      */          
  110.     private Connection newConnection(){          
  111.         try{          
  112.             Class.forName(driver);          
  113.         }catch(ClassNotFoundException e2){          
  114.             e2.printStackTrace();          
  115.         }          
  116.         try{          
  117.             conn = DriverManager.getConnection(url,user,password);          
  118.         }catch(SQLException e3){          
  119.             e3.printStackTrace();          
  120.             System.exit(0);          
  121.         }          
  122.         return conn;          
  123.     }          
  124. }      

最后提供一个连接池的管理类:

 


  1. Java 代码复制内容到剪贴板  
  2.       
  3. import java.sql.Connection;          
  4. import java.util.Enumeration;          
  5. import java.util.Hashtable;          
  6.           
  7. import cn.cate.utils.PoolProperties;          
  8.           
  9. /*       
  10. * 连接池的管理类,负责读取配置连接池的文件,并创建连接池       
  11. * 从连接池中获取,释放连接       
  12. */          
  13. public class DBConnectionManager {          
  14.           
  15.     /*       
  16.      * 唯一数据库连接池管理实例类       
  17.      * 使用单例模式创建       
  18.      */          
  19.     private static DBConnectionManager instance;          
  20.               
  21.     /*       
  22.      * 连接池的集合       
  23.      */          
  24.     private Hashtable<String,DBConnectionPool> pools = new Hashtable<String,DBConnectionPool>();          
  25.     private static String poolName = "MYSQL_MZBA";      //连接池名字          
  26.               
  27.     public static synchronized DBConnectionManager getInstance(){          
  28.         if(instance == null){          
  29.             instance = new DBConnectionManager();          
  30.         }          
  31.         return instance;          
  32.     }          
  33.               
  34.     /*       
  35.      * 只允许内部实例化管理类       
  36.      */          
  37.     private DBConnectionManager(){          
  38.         this.init();          
  39.     }          
  40.               
  41.     /*       
  42.      * 加载驱动程序       
  43.      */          
  44.     private void init(){          
  45.         PoolProperties poolProperties = new PoolProperties();          
  46.         DBConnectionPool pool = new DBConnectionPool(poolProperties.getDriver(), poolProperties.getUrl(),           
  47.                 poolProperties.getUser(), poolProperties.getPassword(), poolProperties.getMaxConn());          
  48.         pools.put(poolName, pool);          
  49.     }          
  50.               
  51.     /*       
  52.      * 根据连接池的名字得到一个连接       
  53.      */          
  54.     public Connection getConnection(){          
  55.         DBConnectionPool pool = null;          
  56.         Connection conn = null;          
  57.         pool = pools.get(poolName);          
  58.         try{          
  59.             conn = pool.getConnection();          
  60.         }catch(Exception e){          
  61.             e.printStackTrace();          
  62.         }          
  63.         return conn;          
  64.     }          
  65.     /*       
  66.      * 释放一个连接       
  67.      */          
  68.     public synchronized void freeConnection(Connection conn){          
  69.         DBConnectionPool pool = pools.get(poolName);          
  70.         if(pool != null){          
  71.             pool.freeConnection(conn);          
  72.         }          
  73.     }          
  74.     /*       
  75.      * 释放所有连接       
  76.      */          
  77.     public synchronized void release(){          
  78.         Enumeration<DBConnectionPool> allpools = pools.elements();          
  79.         while(allpools.hasMoreElements()){          
  80.             DBConnectionPool pool = allpools.nextElement();          
  81.             if(pool != null){          
  82.                 pool.release();          
  83.             }          
  84.         }          
  85.         pools.clear();          
  86.     }          
  87.           
  88. }      

 



     本文转自06peng 51CTO博客,原文链接:http://blog.51cto.com/06peng/962458,如需转载请自行联系原作者