⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 dbconnectionmanager.java

📁 动态网站管理发布系统
💻 JAVA
字号:
package com.ntsky.pool;

import com.ntsky.common.Debug;
import com.ntsky.common.EnvironmentConfig;
import java.sql.*;
import java.util.*;
import java.util.Date;

public class DBConnectionManager {
	class DBConnectionPool {

		private int checkedOut;

		private Vector freeConnections;

		private int maxConn;
		
		private int maxIdleConn;

		private String name;

		private String user;

		private String password;

		private String URL;

		public synchronized void freeConnection(Connection Conn) {
			if(freeConnections.size() >= maxIdleConn){
				freeConnections.removeElementAt(freeConnections.size()-1);
			}
			freeConnections.addElement(Conn);
			checkedOut--;
			notifyAll();
		}

		public synchronized void deleteConnection(Connection Conn) {
			if(freeConnections.contains(Conn)){
				freeConnections.remove(Conn);
				Conn = null;
				checkedOut--;
				notifyAll();				
			}
		}
		
		
		public synchronized Connection getConnection() {
			Connection con = null;
			if (freeConnections.size() > 0) {
				con = (Connection)freeConnections.firstElement();
				freeConnections.removeElementAt(0);
				try {
					if (con.isClosed()) {
						Debug.writeLog("从连接池" + name + "删除一个无效连接");
						Debug.writeLog("重新获取连接");
						con = getConnection();
					}
				} catch (SQLException e) {
					con = getConnection();
				}
			} else if (maxConn == 0 || checkedOut < maxConn) {
				con = newConnection();
			}
			if (con != null)checkedOut++;
			if (con == null)Debug.writeLog("DBConnectionPool getConnection(), The Returned Con is null");
			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;
		}

		private Connection newConnection() {
			Connection con = null;
			try {
				if (user == null){
					con = DriverManager.getConnection(URL);
				}	
				else{
					con = DriverManager.getConnection(URL, user, password);
				}
				Debug.writeLog("连接池" + name + "创建一个新的连接");
			} catch (SQLException e) {
				Debug.writeLog("无法创建下列URL的连接: " + URL);
				e.printStackTrace(System.out);
				return null;
			}
			if (con == null)
				Debug.writeLog("DBConnectionPool newConnection(), The Returned Con is null");
			return con;
		}

		public synchronized void release() {
			for (Enumeration allConnections = freeConnections.elements(); allConnections.hasMoreElements();) {
				Connection con = (Connection) allConnections.nextElement();
				try {
					con.close();
					Debug.writeLog("关闭连接池" + name + "中的一个连接");
				} catch (SQLException e) {
					Debug.writeLog("无法关闭连接池" + name + "中的连接");
					e.printStackTrace(System.out);
				}
			}

			freeConnections.removeAllElements();
		}

		public DBConnectionPool(String name, String url, String user,String password, int maxConn, int maxIdleConn) {
			freeConnections = new Vector();
			this.name = name;
			URL = url;
			this.user = user;
			this.password = password;
			this.maxConn = maxConn;
			this.maxIdleConn = maxIdleConn;
			Debug.writeLog("poolname:" + this.name);
			Debug.writeLog("URL: " + URL);
			Debug.writeLog("user: " + this.user);
			Debug.writeLog("password: " + this.password);
			Debug.writeLog("maxConn: " + this.maxConn);
			Debug.writeLog("maxIdleConn: " + this.maxIdleConn);			
		}
	}

	private static DBConnectionManager instance;

	private static int clients;

	private Vector drivers;

	private Hashtable pools;

	private DBConnectionManager() {
		drivers = new Vector();
		pools = new Hashtable();
		init();
	}

	private void createPools(Properties props) {
		for (Enumeration propNames = props.propertyNames(); propNames.hasMoreElements();) {
			String name = (String) propNames.nextElement();
			Debug.writeLog("createPools(Properties), name is:  " + name);
			if (name.endsWith(".url")) {
				Debug.writeLog("createPools(Properties), name end with url");
				String poolName = name.substring(0, name.lastIndexOf("."));
				String url = props.getProperty(poolName + ".url");
				Debug.writeLog("createPools(Properties), url is " + url);
				if (url == null) {
					Debug.writeLog("没有为连接池" + poolName + "指定URL");
				} else {
					String user = props.getProperty(poolName + ".user");
					String password = props.getProperty(poolName + ".password");
					String maxconn = props.getProperty(poolName + ".maxconn","0");
					int maxIdleConn = Integer.parseInt(props.getProperty(poolName + ".maxIdleConn","0"));
					int max;
					try {
						max = Integer.valueOf(maxconn).intValue();
					} catch (NumberFormatException e) {
						Debug.writeLog("错误的最大连接数限制: " + maxconn + " .连接池: " + poolName);
						max = 0;
					}
					DBConnectionPool pool = new DBConnectionPool(poolName, url, user, password, max, maxIdleConn);
					pools.put(poolName, pool);
					Debug.writeLog("成功创建连接池" + poolName);
				}
			}
		}
	}

	public void freeConnection(String name, Connection con) {
		DBConnectionPool pool = (DBConnectionPool) pools.get(name);
		if (pool != null)pool.freeConnection(con);
	}

	public void deleteConnection(String name, Connection con) {
		DBConnectionPool pool = (DBConnectionPool) pools.get(name);
		if (pool != null)pool.deleteConnection(con);
	}	
	
	public Connection getConnection(String name) {
		DBConnectionPool pool = (DBConnectionPool) pools.get(name);
		if (pool != null) {
			Debug.writeLog("DBConnectionManager getConnection(String) ! pool is not null !");
			return pool.getConnection();
		} else {
			return null;
		}
	}

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

	public static synchronized DBConnectionManager getInstance() {
		if (instance == null)instance = new DBConnectionManager();
		clients++;
		return instance;
	}

	private void init() {
		Properties dbProps = EnvironmentConfig.getInstance().getProperties("/SiteConfig/db.properties");
		loadDrivers(dbProps);
		createPools(dbProps);
	}

	private void loadDrivers(Properties props) {
		String driverClasses = props.getProperty("drivers");
		for (StringTokenizer st = new StringTokenizer(driverClasses); st.hasMoreElements();) {
			String driverClassName = st.nextToken().trim();
			try {
				Driver driver = (Driver) Class.forName(driverClassName).newInstance();
				DriverManager.registerDriver(driver);
				Debug.writeLog("Load Driver Success !");
				drivers.addElement(driver);
				Debug.writeLog("成功注册JDBC驱动程序" + driverClassName);
			} catch (Exception e) {
				Debug.writeLog("无法注册JDBC驱动程序: " + driverClassName + ", 错误: " + e);
			}
		}

	}

	public synchronized void release() {
		if (--clients != 0)return;
		DBConnectionPool pool;
		for (Enumeration allPools = pools.elements(); allPools.hasMoreElements(); pool.release())
			pool = (DBConnectionPool) allPools.nextElement();

		for (Enumeration allDrivers = drivers.elements(); allDrivers.hasMoreElements();) {
			Driver driver = (Driver) allDrivers.nextElement();
			try {
				DriverManager.deregisterDriver(driver);
				Debug.writeLog("撤销JDBC驱动程序 " + driver.getClass().getName()+ "的注册");
			} catch (SQLException e) {
				Debug.writeLog("无法撤销下列JDBC驱动程序的注册: " + driver.getClass().getName());
				e.printStackTrace(System.out);
			}
		}

	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -