java的幾種連接池


連接池的管理用了了享元模式,這里對連接池進行簡單設計。

一、設計思路

     1.連接池配置屬性DBbean:里面存放可以配置的一些屬性

     2.連接池接口IConnectionPool:里面定義一些基本的獲取連接的一些方法

     3.接口實現ConnectionPool:對上面操作進行實現,並加入一些其他方法

     4.連接池管理ConnectionPoolManager:管理所有的不同的連接池,所有的連接都能通過這里進行獲得連接

     5.另外還有幾個測試類,和連接信息模擬的類,這里就不進行xml 和配置文件信息的讀取了

Java代碼   收藏代碼
  1. package pool;  
  2. /** 
  3.  * 這是外部可以配置的連接池屬性 
  4.  * 可以允許外部配置,擁有默認值 
  5.  * @author Ran 
  6.  * 
  7.  */  
  8. public class DBbean {  
  9.     // 連接池屬性  
  10.     private String driverName;  
  11.     private String url;  
  12.     private String userName;  
  13.     private String password;  
  14.     // 連接池名字  
  15.     private String poolName;  
  16.     private int minConnections = 1// 空閑池,最小連接數  
  17.     private int maxConnections = 10// 空閑池,最大連接數  
  18.       
  19.     private int initConnections = 5;// 初始化連接數  
  20.       
  21.     private long connTimeOut = 1000;// 重復獲得連接的頻率  
  22.       
  23.     private int maxActiveConnections = 100;// 最大允許的連接數,和數據庫對應  
  24.       
  25.     private long connectionTimeOut = 1000*60*20;// 連接超時時間,默認20分鍾  
  26.       
  27.     private boolean isCurrentConnection = true; // 是否獲得當前連接,默認true  
  28.       
  29.     private boolean isCheakPool = true; // 是否定時檢查連接池  
  30.     private long lazyCheck = 1000*60*60;// 延遲多少時間后開始 檢查  
  31.     private long periodCheck = 1000*60*60;// 檢查頻率  
  32.       
  33.       
  34.       
  35.     public DBbean(String driverName, String url, String userName,  
  36.             String password, String poolName) {  
  37.         super();  
  38.         this.driverName = driverName;  
  39.         this.url = url;  
  40.         this.userName = userName;  
  41.         this.password = password;  
  42.         this.poolName = poolName;  
  43.     }  
  44.     public DBbean() {  
  45.     }  
  46.     public String getDriverName() {  
  47.         if(driverName == null){  
  48.             driverName = this.getDriverName()+"_"+this.getUrl();  
  49.         }  
  50.         return driverName;  
  51.     }  
  52.     public void setDriverName(String driverName) {  
  53.         this.driverName = driverName;  
  54.     }  
  55.     public String getUrl() {  
  56.         return url;  
  57.     }  
  58.     public void setUrl(String url) {  
  59.         this.url = url;  
  60.     }  
  61.     public String getUserName() {  
  62.         return userName;  
  63.     }  
  64.     public void setUserName(String userName) {  
  65.         this.userName = userName;  
  66.     }  
  67.     public String getPassword() {  
  68.         return password;  
  69.     }  
  70.     public void setPassword(String password) {  
  71.         this.password = password;  
  72.     }  
  73.     public String getPoolName() {  
  74.         return poolName;  
  75.     }  
  76.     public void setPoolName(String poolName) {  
  77.         this.poolName = poolName;  
  78.     }  
  79.     public int getMinConnections() {  
  80.         return minConnections;  
  81.     }  
  82.     public void setMinConnections(int minConnections) {  
  83.         this.minConnections = minConnections;  
  84.     }  
  85.     public int getMaxConnections() {  
  86.         return maxConnections;  
  87.     }  
  88.     public void setMaxConnections(int maxConnections) {  
  89.         this.maxConnections = maxConnections;  
  90.     }  
  91.     public int getInitConnections() {  
  92.         return initConnections;  
  93.     }  
  94.     public void setInitConnections(int initConnections) {  
  95.         this.initConnections = initConnections;  
  96.     }  
  97.   
  98.     public int getMaxActiveConnections() {  
  99.         return maxActiveConnections;  
  100.     }  
  101.     public void setMaxActiveConnections(int maxActiveConnections) {  
  102.         this.maxActiveConnections = maxActiveConnections;  
  103.     }  
  104.     public long getConnTimeOut() {  
  105.         return connTimeOut;  
  106.     }  
  107.     public void setConnTimeOut(long connTimeOut) {  
  108.         this.connTimeOut = connTimeOut;  
  109.     }  
  110.     public long getConnectionTimeOut() {  
  111.         return connectionTimeOut;  
  112.     }  
  113.     public void setConnectionTimeOut(long connectionTimeOut) {  
  114.         this.connectionTimeOut = connectionTimeOut;  
  115.     }  
  116.     public boolean isCurrentConnection() {  
  117.         return isCurrentConnection;  
  118.     }  
  119.     public void setCurrentConnection(boolean isCurrentConnection) {  
  120.         this.isCurrentConnection = isCurrentConnection;  
  121.     }  
  122.     public long getLazyCheck() {  
  123.         return lazyCheck;  
  124.     }  
  125.     public void setLazyCheck(long lazyCheck) {  
  126.         this.lazyCheck = lazyCheck;  
  127.     }  
  128.     public long getPeriodCheck() {  
  129.         return periodCheck;  
  130.     }  
  131.     public void setPeriodCheck(long periodCheck) {  
  132.         this.periodCheck = periodCheck;  
  133.     }  
  134.     public boolean isCheakPool() {  
  135.         return isCheakPool;  
  136.     }  
  137.     public void setCheakPool(boolean isCheakPool) {  
  138.         this.isCheakPool = isCheakPool;  
  139.     }  
  140.       
  141.       
  142.       
  143. }  
package pool;
/**
 * 這是外部可以配置的連接池屬性
 * 可以允許外部配置,擁有默認值
 * @author Ran
 *
 */
public class DBbean {
	// 連接池屬性
	private String driverName;
	private String url;
	private String userName;
	private String password;
	// 連接池名字
	private String poolName;
	private int minConnections = 1; // 空閑池,最小連接數
	private int maxConnections = 10; // 空閑池,最大連接數
	
	private int initConnections = 5;// 初始化連接數
	
	private long connTimeOut = 1000;// 重復獲得連接的頻率
	
	private int maxActiveConnections = 100;// 最大允許的連接數,和數據庫對應
	
	private long connectionTimeOut = 1000*60*20;// 連接超時時間,默認20分鍾
	
	private boolean isCurrentConnection = true; // 是否獲得當前連接,默認true
	
	private boolean isCheakPool = true; // 是否定時檢查連接池
	private long lazyCheck = 1000*60*60;// 延遲多少時間后開始 檢查
	private long periodCheck = 1000*60*60;// 檢查頻率
	
	
	
	public DBbean(String driverName, String url, String userName,
			String password, String poolName) {
		super();
		this.driverName = driverName;
		this.url = url;
		this.userName = userName;
		this.password = password;
		this.poolName = poolName;
	}
	public DBbean() {
	}
	public String getDriverName() {
		if(driverName == null){
			driverName = this.getDriverName()+"_"+this.getUrl();
		}
		return driverName;
	}
	public void setDriverName(String driverName) {
		this.driverName = driverName;
	}
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getPoolName() {
		return poolName;
	}
	public void setPoolName(String poolName) {
		this.poolName = poolName;
	}
	public int getMinConnections() {
		return minConnections;
	}
	public void setMinConnections(int minConnections) {
		this.minConnections = minConnections;
	}
	public int getMaxConnections() {
		return maxConnections;
	}
	public void setMaxConnections(int maxConnections) {
		this.maxConnections = maxConnections;
	}
	public int getInitConnections() {
		return initConnections;
	}
	public void setInitConnections(int initConnections) {
		this.initConnections = initConnections;
	}

	public int getMaxActiveConnections() {
		return maxActiveConnections;
	}
	public void setMaxActiveConnections(int maxActiveConnections) {
		this.maxActiveConnections = maxActiveConnections;
	}
	public long getConnTimeOut() {
		return connTimeOut;
	}
	public void setConnTimeOut(long connTimeOut) {
		this.connTimeOut = connTimeOut;
	}
	public long getConnectionTimeOut() {
		return connectionTimeOut;
	}
	public void setConnectionTimeOut(long connectionTimeOut) {
		this.connectionTimeOut = connectionTimeOut;
	}
	public boolean isCurrentConnection() {
		return isCurrentConnection;
	}
	public void setCurrentConnection(boolean isCurrentConnection) {
		this.isCurrentConnection = isCurrentConnection;
	}
	public long getLazyCheck() {
		return lazyCheck;
	}
	public void setLazyCheck(long lazyCheck) {
		this.lazyCheck = lazyCheck;
	}
	public long getPeriodCheck() {
		return periodCheck;
	}
	public void setPeriodCheck(long periodCheck) {
		this.periodCheck = periodCheck;
	}
	public boolean isCheakPool() {
		return isCheakPool;
	}
	public void setCheakPool(boolean isCheakPool) {
		this.isCheakPool = isCheakPool;
	}
	
	
	
}

 

Java代碼   收藏代碼
  1. package pool;  
  2.   
  3. import java.sql.Connection;  
  4. import java.sql.SQLException;  
  5.   
  6. public interface IConnectionPool {  
  7.     // 獲得連接  
  8.     public Connection  getConnection();  
  9.     // 獲得當前連接  
  10.     public Connection getCurrentConnecton();  
  11.     // 回收連接  
  12.     public void releaseConn(Connection conn) throws SQLException;  
  13.     // 銷毀清空  
  14.     public void destroy();  
  15.     // 連接池是活動狀態  
  16.     public boolean isActive();  
  17.     // 定時器,檢查連接池  
  18.     public void cheackPool();  
  19. }  
package pool;

import java.sql.Connection;
import java.sql.SQLException;

public interface IConnectionPool {
	// 獲得連接
	public Connection  getConnection();
	// 獲得當前連接
	public Connection getCurrentConnecton();
	// 回收連接
	public void releaseConn(Connection conn) throws SQLException;
	// 銷毀清空
	public void destroy();
	// 連接池是活動狀態
	public boolean isActive();
	// 定時器,檢查連接池
	public void cheackPool();
}

 

Java代碼   收藏代碼
  1. package pool;  
  2.   
  3. import java.sql.Connection;  
  4. import java.sql.DriverManager;  
  5. import java.sql.SQLException;  
  6. import java.util.List;  
  7. import java.util.Timer;  
  8. import java.util.TimerTask;  
  9. import java.util.Vector;  
  10.   
  11. public class ConnectionPool implements IConnectionPool {  
  12.     // 連接池配置屬性  
  13.     private DBbean dbBean;  
  14.     private boolean isActive = false; // 連接池活動狀態  
  15.     private int contActive = 0;// 記錄創建的總的連接數  
  16.       
  17.     // 空閑連接  
  18.     private List<Connection> freeConnection = new Vector<Connection>();  
  19.     // 活動連接  
  20.     private List<Connection> activeConnection = new Vector<Connection>();  
  21.     // 將線程和連接綁定,保證事務能統一執行  
  22.     private static ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();  
  23.       
  24.     public ConnectionPool(DBbean dbBean) {  
  25.         super();  
  26.         this.dbBean = dbBean;  
  27.         init();  
  28.         cheackPool();  
  29.     }  
  30.   
  31.     // 初始化  
  32.     public void init() {  
  33.         try {  
  34.             Class.forName(dbBean.getDriverName());  
  35.             for (int i = 0; i < dbBean.getInitConnections(); i++) {  
  36.                 Connection conn;  
  37.                 conn = newConnection();  
  38.                 // 初始化最小連接數  
  39.                 if (conn != null) {  
  40.                     freeConnection.add(conn);  
  41.                     contActive++;  
  42.                 }  
  43.             }  
  44.             isActive = true;  
  45.         } catch (ClassNotFoundException e) {  
  46.             e.printStackTrace();  
  47.         } catch (SQLException e) {  
  48.             e.printStackTrace();  
  49.         }  
  50.     }  
  51.       
  52.     // 獲得當前連接  
  53.     public Connection getCurrentConnecton(){  
  54.         // 默認線程里面取  
  55.         Connection conn = threadLocal.get();  
  56.         if(!isValid(conn)){  
  57.             conn = getConnection();  
  58.         }  
  59.         return conn;  
  60.     }  
  61.   
  62.     // 獲得連接  
  63.     public synchronized Connection getConnection() {  
  64.         Connection conn = null;  
  65.         try {  
  66.             // 判斷是否超過最大連接數限制  
  67.             if(contActive < this.dbBean.getMaxActiveConnections()){  
  68.                 if (freeConnection.size() > 0) {  
  69.                     conn = freeConnection.get(0);  
  70.                     if (conn != null) {  
  71.                         threadLocal.set(conn);  
  72.                     }  
  73.                     freeConnection.remove(0);  
  74.                 } else {  
  75.                     conn = newConnection();  
  76.                 }  
  77.                   
  78.             }else{  
  79.                 // 繼續獲得連接,直到從新獲得連接  
  80.                 wait(this.dbBean.getConnTimeOut());  
  81.                 conn = getConnection();  
  82.             }  
  83.             if (isValid(conn)) {  
  84.                 activeConnection.add(conn);  
  85.                 contActive ++;  
  86.             }  
  87.         } catch (SQLException e) {  
  88.             e.printStackTrace();  
  89.         } catch (ClassNotFoundException e) {  
  90.             e.printStackTrace();  
  91.         } catch (InterruptedException e) {  
  92.             e.printStackTrace();  
  93.         }  
  94.         return conn;  
  95.     }  
  96.   
  97.     // 獲得新連接  
  98.     private synchronized Connection newConnection()  
  99.             throws ClassNotFoundException, SQLException {  
  100.         Connection conn = null;  
  101.         if (dbBean != null) {  
  102.             Class.forName(dbBean.getDriverName());  
  103.             conn = DriverManager.getConnection(dbBean.getUrl(),  
  104.                     dbBean.getUserName(), dbBean.getPassword());  
  105.         }  
  106.         return conn;  
  107.     }  
  108.   
  109.     // 釋放連接  
  110.     public synchronized void releaseConn(Connection conn) throws SQLException {  
  111.         if (isValid(conn)&& !(freeConnection.size() > dbBean.getMaxConnections())) {  
  112.             freeConnection.add(conn);  
  113.             activeConnection.remove(conn);  
  114.             contActive --;  
  115.             threadLocal.remove();  
  116.             // 喚醒所有正待等待的線程,去搶連接  
  117.             notifyAll();  
  118.         }  
  119.     }  
  120.   
  121.     // 判斷連接是否可用  
  122.     private boolean isValid(Connection conn) {  
  123.         try {  
  124.             if (conn == null || conn.isClosed()) {  
  125.                 return false;  
  126.             }  
  127.         } catch (SQLException e) {  
  128.             e.printStackTrace();  
  129.         }  
  130.         return true;  
  131.     }  
  132.   
  133.     // 銷毀連接池  
  134.     public synchronized void destroy() {  
  135.         for (Connection conn : freeConnection) {  
  136.             try {  
  137.                 if (isValid(conn)) {  
  138.                     conn.close();  
  139.                 }  
  140.             } catch (SQLException e) {  
  141.                 e.printStackTrace();  
  142.             }  
  143.         }  
  144.         for (Connection conn : activeConnection) {  
  145.             try {  
  146.                 if (isValid(conn)) {  
  147.                     conn.close();  
  148.                 }  
  149.             } catch (SQLException e) {  
  150.                 e.printStackTrace();  
  151.             }  
  152.         }  
  153.         isActive = false;  
  154.         contActive = 0;  
  155.     }  
  156.   
  157.     // 連接池狀態  
  158.     @Override  
  159.     public boolean isActive() {  
  160.         return isActive;  
  161.     }  
  162.       
  163.     // 定時檢查連接池情況  
  164.     @Override  
  165.     public void cheackPool() {  
  166.         if(dbBean.isCheakPool()){  
  167.             new Timer().schedule(new TimerTask() {  
  168.             @Override  
  169.             public void run() {  
  170.             // 1.對線程里面的連接狀態  
  171.             // 2.連接池最小 最大連接數  
  172.             // 3.其他狀態進行檢查,因為這里還需要寫幾個線程管理的類,暫時就不添加了  
  173.             System.out.println("空線池連接數:"+freeConnection.size());  
  174.             System.out.println("活動連接數::"+activeConnection.size());  
  175.             System.out.println("總的連接數:"+contActive);  
  176.                 }  
  177.             },dbBean.getLazyCheck(),dbBean.getPeriodCheck());  
  178.         }  
  179.     }  
  180. }  
package pool;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;

public class ConnectionPool implements IConnectionPool {
	// 連接池配置屬性
	private DBbean dbBean;
	private boolean isActive = false; // 連接池活動狀態
	private int contActive = 0;// 記錄創建的總的連接數
	
	// 空閑連接
	private List<Connection> freeConnection = new Vector<Connection>();
	// 活動連接
	private List<Connection> activeConnection = new Vector<Connection>();
	// 將線程和連接綁定,保證事務能統一執行
	private static ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();
	
	public ConnectionPool(DBbean dbBean) {
		super();
		this.dbBean = dbBean;
		init();
		cheackPool();
	}

	// 初始化
	public void init() {
		try {
			Class.forName(dbBean.getDriverName());
			for (int i = 0; i < dbBean.getInitConnections(); i++) {
				Connection conn;
				conn = newConnection();
				// 初始化最小連接數
				if (conn != null) {
					freeConnection.add(conn);
					contActive++;
				}
			}
			isActive = true;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	// 獲得當前連接
	public Connection getCurrentConnecton(){
		// 默認線程里面取
		Connection conn = threadLocal.get();
		if(!isValid(conn)){
			conn = getConnection();
		}
		return conn;
	}

	// 獲得連接
	public synchronized Connection getConnection() {
		Connection conn = null;
		try {
			// 判斷是否超過最大連接數限制
			if(contActive < this.dbBean.getMaxActiveConnections()){
				if (freeConnection.size() > 0) {
					conn = freeConnection.get(0);
					if (conn != null) {
						threadLocal.set(conn);
					}
					freeConnection.remove(0);
				} else {
					conn = newConnection();
				}
				
			}else{
				// 繼續獲得連接,直到從新獲得連接
				wait(this.dbBean.getConnTimeOut());
				conn = getConnection();
			}
			if (isValid(conn)) {
				activeConnection.add(conn);
				contActive ++;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return conn;
	}

	// 獲得新連接
	private synchronized Connection newConnection()
			throws ClassNotFoundException, SQLException {
		Connection conn = null;
		if (dbBean != null) {
			Class.forName(dbBean.getDriverName());
			conn = DriverManager.getConnection(dbBean.getUrl(),
					dbBean.getUserName(), dbBean.getPassword());
		}
		return conn;
	}

	// 釋放連接
	public synchronized void releaseConn(Connection conn) throws SQLException {
		if (isValid(conn)&& !(freeConnection.size() > dbBean.getMaxConnections())) {
			freeConnection.add(conn);
			activeConnection.remove(conn);
			contActive --;
			threadLocal.remove();
			// 喚醒所有正待等待的線程,去搶連接
			notifyAll();
		}
	}

	// 判斷連接是否可用
	private boolean isValid(Connection conn) {
		try {
			if (conn == null || conn.isClosed()) {
				return false;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return true;
	}

	// 銷毀連接池
	public synchronized void destroy() {
		for (Connection conn : freeConnection) {
			try {
				if (isValid(conn)) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		for (Connection conn : activeConnection) {
			try {
				if (isValid(conn)) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		isActive = false;
		contActive = 0;
	}

	// 連接池狀態
	@Override
	public boolean isActive() {
		return isActive;
	}
	
	// 定時檢查連接池情況
	@Override
	public void cheackPool() {
		if(dbBean.isCheakPool()){
			new Timer().schedule(new TimerTask() {
			@Override
			public void run() {
			// 1.對線程里面的連接狀態
			// 2.連接池最小 最大連接數
			// 3.其他狀態進行檢查,因為這里還需要寫幾個線程管理的類,暫時就不添加了
			System.out.println("空線池連接數:"+freeConnection.size());
			System.out.println("活動連接數::"+activeConnection.size());
			System.out.println("總的連接數:"+contActive);
				}
			},dbBean.getLazyCheck(),dbBean.getPeriodCheck());
		}
	}
}

 

Java代碼   收藏代碼
  1. package pool;  
  2.   
  3. import java.sql.Connection;  
  4. import java.sql.SQLException;  
  5. import java.util.Hashtable;  
  6. /** 
  7.  * 連接管理類 
  8.  * @author Ran 
  9.  * 
  10.  */  
  11. public class ConnectionPoolManager {  
  12.       
  13.       
  14.     // 連接池存放  
  15.     public Hashtable<String,IConnectionPool> pools = new Hashtable<String, IConnectionPool>();  
  16.       
  17.     // 初始化  
  18.     private ConnectionPoolManager(){  
  19.         init();  
  20.     }  
  21.     // 單例實現  
  22.     public static ConnectionPoolManager getInstance(){  
  23.         return Singtonle.instance;  
  24.     }  
  25.     private static class Singtonle {  
  26.         private static ConnectionPoolManager instance =  new ConnectionPoolManager();  
  27.     }  
  28.       
  29.       
  30.     // 初始化所有的連接池  
  31.     public void init(){  
  32.         for(int i =0;i<DBInitInfo.beans.size();i++){  
  33.             DBbean bean = DBInitInfo.beans.get(i);  
  34.             ConnectionPool pool = new ConnectionPool(bean);  
  35.             if(pool != null){  
  36.                 pools.put(bean.getPoolName(), pool);  
  37.                 System.out.println("Info:Init connection successed ->" +bean.getPoolName());  
  38.             }  
  39.         }  
  40.     }  
  41.       
  42.     // 獲得連接,根據連接池名字 獲得連接  
  43.     public Connection  getConnection(String poolName){  
  44.         Connection conn = null;  
  45.         if(pools.size()>0 && pools.containsKey(poolName)){  
  46.             conn = getPool(poolName).getConnection();  
  47.         }else{  
  48.             System.out.println("Error:Can't find this connecion pool ->"+poolName);  
  49.         }  
  50.         return conn;  
  51.     }  
  52.       
  53.     // 關閉,回收連接  
  54.     public void close(String poolName,Connection conn){  
  55.             IConnectionPool pool = getPool(poolName);  
  56.             try {  
  57.                 if(pool != null){  
  58.                     pool.releaseConn(conn);  
  59.                 }  
  60.             } catch (SQLException e) {  
  61.                 System.out.println("連接池已經銷毀");  
  62.                 e.printStackTrace();  
  63.             }  
  64.     }  
  65.       
  66.     // 清空連接池  
  67.     public void destroy(String poolName){  
  68.         IConnectionPool pool = getPool(poolName);  
  69.         if(pool != null){  
  70.             pool.destroy();  
  71.         }  
  72.     }  
  73.       
  74.     // 獲得連接池  
  75.     public IConnectionPool getPool(String poolName){  
  76.         IConnectionPool pool = null;  
  77.         if(pools.size() > 0){  
  78.              pool = pools.get(poolName);  
  79.         }  
  80.         return pool;  
  81.     }  
  82. }  
package pool;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Hashtable;
/**
 * 連接管理類
 * @author Ran
 *
 */
public class ConnectionPoolManager {
	
	
	// 連接池存放
	public Hashtable<String,IConnectionPool> pools = new Hashtable<String, IConnectionPool>();
	
	// 初始化
	private ConnectionPoolManager(){
		init();
	}
	// 單例實現
	public static ConnectionPoolManager getInstance(){
		return Singtonle.instance;
	}
	private static class Singtonle {
		private static ConnectionPoolManager instance =  new ConnectionPoolManager();
	}
	
	
	// 初始化所有的連接池
	public void init(){
		for(int i =0;i<DBInitInfo.beans.size();i++){
			DBbean bean = DBInitInfo.beans.get(i);
			ConnectionPool pool = new ConnectionPool(bean);
			if(pool != null){
				pools.put(bean.getPoolName(), pool);
				System.out.println("Info:Init connection successed ->" +bean.getPoolName());
			}
		}
	}
	
	// 獲得連接,根據連接池名字 獲得連接
	public Connection  getConnection(String poolName){
		Connection conn = null;
		if(pools.size()>0 && pools.containsKey(poolName)){
			conn = getPool(poolName).getConnection();
		}else{
			System.out.println("Error:Can't find this connecion pool ->"+poolName);
		}
		return conn;
	}
	
	// 關閉,回收連接
	public void close(String poolName,Connection conn){
			IConnectionPool pool = getPool(poolName);
			try {
				if(pool != null){
					pool.releaseConn(conn);
				}
			} catch (SQLException e) {
				System.out.println("連接池已經銷毀");
				e.printStackTrace();
			}
	}
	
	// 清空連接池
	public void destroy(String poolName){
		IConnectionPool pool = getPool(poolName);
		if(pool != null){
			pool.destroy();
		}
	}
	
	// 獲得連接池
	public IConnectionPool getPool(String poolName){
		IConnectionPool pool = null;
		if(pools.size() > 0){
			 pool = pools.get(poolName);
		}
		return pool;
	}
}

 

Java代碼   收藏代碼
  1. package pool;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5. /** 
  6.  * 初始化,模擬加載所有的配置文件 
  7.  * @author Ran 
  8.  * 
  9.  */  
  10. public class DBInitInfo {  
  11.     public  static List<DBbean>  beans = null;  
  12.     static{  
  13.         beans = new ArrayList<DBbean>();  
  14.         // 這里數據 可以從xml 等配置文件進行獲取  
  15.         // 為了測試,這里我直接寫死  
  16.         DBbean beanOracle = new DBbean();  
  17.         beanOracle.setDriverName("oracle.jdbc.driver.OracleDriver");  
  18.         beanOracle.setUrl("jdbc:oracle:thin:@7MEXGLUY95W1Y56:1521:orcl");  
  19.         beanOracle.setUserName("mmsoa");  
  20.         beanOracle.setPassword("password1234");  
  21.           
  22.         beanOracle.setMinConnections(5);  
  23.         beanOracle.setMaxConnections(100);  
  24.           
  25.         beanOracle.setPoolName("testPool");  
  26.         beans.add(beanOracle);  
  27.     }  
  28. }  
package pool;

import java.util.ArrayList;
import java.util.List;
/**
 * 初始化,模擬加載所有的配置文件
 * @author Ran
 *
 */
public class DBInitInfo {
	public  static List<DBbean>  beans = null;
	static{
		beans = new ArrayList<DBbean>();
		// 這里數據 可以從xml 等配置文件進行獲取
		// 為了測試,這里我直接寫死
		DBbean beanOracle = new DBbean();
		beanOracle.setDriverName("oracle.jdbc.driver.OracleDriver");
		beanOracle.setUrl("jdbc:oracle:thin:@7MEXGLUY95W1Y56:1521:orcl");
		beanOracle.setUserName("mmsoa");
		beanOracle.setPassword("password1234");
		
		beanOracle.setMinConnections(5);
		beanOracle.setMaxConnections(100);
		
		beanOracle.setPoolName("testPool");
		beans.add(beanOracle);
	}
}

 

    測試:

   

Java代碼   收藏代碼
  1. package pool;  
  2.   
  3. import java.sql.Connection;  
  4. /** 
  5.  * 模擬線程啟動,去獲得連接 
  6.  * @author Ran 
  7.  * 
  8.  */  
  9. public class ThreadConnection implements Runnable{  
  10.     private IConnectionPool pool;  
  11.     @Override  
  12.     public void run() {  
  13.         pool = ConnectionPoolManager.getInstance().getPool("testPool");  
  14.     }  
  15.       
  16.     public Connection getConnection(){  
  17.         Connection conn = null;  
  18.         if(pool != null && pool.isActive()){  
  19.             conn = pool.getConnection();  
  20.         }  
  21.         return conn;  
  22.     }  
  23.       
  24.     public Connection getCurrentConnection(){  
  25.         Connection conn = null;  
  26.         if(pool != null && pool.isActive()){  
  27.             conn = pool.getCurrentConnecton();  
  28.         }  
  29.         return conn;  
  30.     }  
  31. }  
package pool;

import java.sql.Connection;
/**
 * 模擬線程啟動,去獲得連接
 * @author Ran
 *
 */
public class ThreadConnection implements Runnable{
	private IConnectionPool pool;
	@Override
	public void run() {
		pool = ConnectionPoolManager.getInstance().getPool("testPool");
	}
	
	public Connection getConnection(){
		Connection conn = null;
		if(pool != null && pool.isActive()){
			conn = pool.getConnection();
		}
		return conn;
	}
	
	public Connection getCurrentConnection(){
		Connection conn = null;
		if(pool != null && pool.isActive()){
			conn = pool.getCurrentConnecton();
		}
		return conn;
	}
}

 

Java代碼   收藏代碼
  1. package pool;  
  2.   
  3.   
  4.   
  5. public class Client {  
  6.     public static void main(String[] args) throws InterruptedException {  
  7.         // 初始化連接池  
  8.         Thread t = init();  
  9.         t.start();  
  10.         t.join();  
  11.           
  12.         ThreadConnection a = new ThreadConnection();  
  13.         ThreadConnection b = new ThreadConnection();  
  14.         ThreadConnection c = new ThreadConnection();  
  15.         Thread t1 = new Thread(a);  
  16.         Thread t2 = new Thread(b);  
  17.         Thread t3 = new Thread(c);  
  18.           
  19.           
  20.         // 設置優先級,先讓初始化執行,模擬 線程池 先啟動  
  21.         // 這里僅僅表面控制了,因為即使t 線程先啟動,也不能保證pool 初始化完成,為了簡單模擬,這里先這樣寫了  
  22.         t1.setPriority(10);  
  23.         t2.setPriority(10);  
  24.         t3.setPriority(10);  
  25.         t1.start();  
  26.         t2.start();  
  27.         t3.start();  
  28.           
  29.         System.out.println("線程A-> "+a.getConnection());  
  30.         System.out.println("線程B-> "+b.getConnection());  
  31.         System.out.println("線程C-> "+c.getConnection());  
  32.     }  
  33.   
  34.     // 初始化  
  35.     public static Thread init() {  
  36.         Thread t = new Thread(new Runnable() {  
  37.             @Override  
  38.             public void run() {  
  39.                 IConnectionPool  pool = initPool();  
  40.                 while(pool == null || !pool.isActive()){  
  41.                     pool = initPool();  
  42.                 }  
  43.             }  
  44.         });  
  45.         return t;  
  46.     }  
  47.       
  48.     public static IConnectionPool initPool(){  
  49.         return ConnectionPoolManager.getInstance().getPool("testPool");  
  50.     }  
  51.   
  52. }  
package pool;



public class Client {
	public static void main(String[] args) throws InterruptedException {
		// 初始化連接池
		Thread t = init();
		t.start();
		t.join();
		
		ThreadConnection a = new ThreadConnection();
		ThreadConnection b = new ThreadConnection();
		ThreadConnection c = new ThreadConnection();
		Thread t1 = new Thread(a);
		Thread t2 = new Thread(b);
		Thread t3 = new Thread(c);
		
		
		// 設置優先級,先讓初始化執行,模擬 線程池 先啟動
		// 這里僅僅表面控制了,因為即使t 線程先啟動,也不能保證pool 初始化完成,為了簡單模擬,這里先這樣寫了
		t1.setPriority(10);
		t2.setPriority(10);
		t3.setPriority(10);
		t1.start();
		t2.start();
		t3.start();
		
		System.out.println("線程A-> "+a.getConnection());
		System.out.println("線程B-> "+b.getConnection());
		System.out.println("線程C-> "+c.getConnection());
	}

	// 初始化
	public static Thread init() {
		Thread t = new Thread(new Runnable() {
			@Override
			public void run() {
				IConnectionPool  pool = initPool();
				while(pool == null || !pool.isActive()){
					pool = initPool();
				}
			}
		});
		return t;
	}
	
	public static IConnectionPool initPool(){
		return ConnectionPoolManager.getInstance().getPool("testPool");
	}

}

 

小結 :

          1.連接池誕生原因是,如果每次都從數據庫獲得連接,時間比較長,因此我們提前做建立一些連接,放在連接池里面,每次都從里面取

          2.上面僅僅寫了連接池基本原理,關於多線程下連接池的管理沒寫,后面對多線程操作熟練了添加吧


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM