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

📄 pooledconnectionmgr.java

📁 本人课程设计时做的一个用struts框架实现的基于cmmi2的项目管理系统的原型。还有部分功能尚未实现
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
package com.cmmi2pms.common.comdb;import java.sql.DriverManager;//import java.sql.Connection;/** * <p>This class which is a singleton serves as a JDBC connection repository.  * Since creating database connections is one of the most time * intensive aspects of JDBC, we'll create a pool of connections. * Each connection can be used and then replaced back into the * pool. * * <p>A properties file 'ConnectionPool.conf' will be used to * specify the pool's detail. The format of the configuration file is: * *   #(comment) *   JDBCDriver=<JDBC driver name> *   JDBCConnectionURL=<JDBC Connection URL> *   ConnectionPoolSize=<minimum size of the pool> *   ConnectionPoolMax=<maximum size of the pool, or -1 for none> *   ConnectionUseCount=<maximum usage count for one connection> *   ConnectionTimeout=<maximum idle lifetime (in minutes) of *        a connection> *   <other property for JDBC connection>=<value> * * <p>Any number of additional properties may be given (such * as username and password) as required by the JDBC driver. *  * @author xunzy * @version 0.01 * */public class PooledConnectionMgr implements com.cmmi2pms.common.timer.TimerListener{	private static final PooledConnectionMgr pcm=new PooledConnectionMgr();		// JDBC Driver name	String JDBCDriver;		// JDBC Connection URL	String JDBCConnectionURL;		String userName = "root";	String passWord = "";	// Minimum size of the pool	int connectionPoolSize;		// Maximum size of the pool	int connectionPoolMax;		// Maximum number of uses for a single connection, or -1 for	// none	int connectionUseCount;		// Maximum connection idle time (in minutes)	int connectionTimeout;		//Maximum waiting for connection time	int waitTimeOut;	// The Connection pool. This is a vector of PooledConnection	// objects	java.util.Vector pool;		// The maximum number of simultaneous connections as reported	// by the JDBC driver	int maxConnections = -1;		// Our Timer object	com.cmmi2pms.common.timer.Timer timer;		private PooledConnectionMgr(){}		/**	* <p>Initializes the PooledConnectionMgr object using	* 'ConnectionPool.conf' as the configuration file	*	* @return true if the PooledConnectionMgr was initialized	* properly	*/	public void setUserName( String a_userName )	{		userName = a_userName;	}	public void setPassWord( String a_passWord )	{		passWord = a_passWord;	}	void setJDBCDriver( String a_JDBCDriver )	{		JDBCDriver = a_JDBCDriver;	}	void setJDBCConnectionURL( String a_JDBCConnectionURL )	{		JDBCConnectionURL = a_JDBCConnectionURL;	}	void setConnectionPoolSize( int a_connectionPoolSize )	{		connectionPoolSize = a_connectionPoolSize;	}	void setConnectionPoolMax( int a_connectionPoolMax )	{		connectionPoolMax = a_connectionPoolMax;	}	void setConnectionUseCount( int a_connectionUseCount )	{		connectionUseCount = a_connectionUseCount;	}	void setConnectionTimeout( int a_connectionTimeout )	{		connectionTimeout = a_connectionTimeout;	}	void setWaitTimeOut( int a_waitTimeOut )	{		waitTimeOut = a_waitTimeOut;	}		public static PooledConnectionMgr getInstance()	{		return pcm;	}		public void initialize(int timeCheck,String ip,int port,String dbName ) throws Exception	{		//get conf.This is default;		PooledConnectionMgr.getInstance().setJDBCDriver( "org.gjt.mm.mysql.Driver" );		PooledConnectionMgr.getInstance().setJDBCConnectionURL( "jdbc:mysql://"+ip+":"+port+"/"+dbName+"?useUnicode=true&characterEncoding=GBK" );		PooledConnectionMgr.getInstance().setConnectionPoolSize( 5 );		PooledConnectionMgr.getInstance().setConnectionPoolMax( 10 );		PooledConnectionMgr.getInstance().setConnectionUseCount( 8 );		PooledConnectionMgr.getInstance().setConnectionTimeout( 30 );		// Properties were loaded; attempt to create our pool of connections		// logFile = new LogFile( logFileName );		//System.out.println( "-------建立数据库连接池-------" );		////System.out.println("ConnectionTimecheck = " + timeCheck + "seconds" );		createPool();				// Start our timer so we can timeout connections. The		// clock cycle will be 20 seconds		timer = new com.cmmi2pms.common.timer.Timer(this, timeCheck );		timer.start();	}	/**	* <p>Destroys the pool and it's contents. Closes any open	* JDBC connections and frees all resources	*/	public void destroy()	{		//System.out.println( "-------数据库连接池撤销-------" );		//System.out.println( "数据库连接池大小="+pool.size() );		try 		{					// Stop our timer thread			if (timer != null)			{				timer.end();				synchronized (timer)				{					timer.notify();				};				//System.out.println( "等待定时器结束..." );				while ( timer.getRunFlag() ){}				timer = null;				//System.out.println( "定时器结束" ); 			}						// Clear our pool			if (pool != null)			{				//System.out.println( "开始删除连接..." );				// Loop throught the pool and close each connection				for (int i = 0; i < pool.size(); i++)				{					close((PooledConnection) pool.elementAt(i));				}			}			pool = null;		}		catch (Exception ex)		{			ex.printStackTrace();		}	}	/**	* <p>Gets an available JDBC Connection. Connections will be	* created if necessary, up to the maximum number of connections	* as specified in the configuration file.	*	* @return JDBC Connection, or null if the maximum	* number of connections has been exceeded	*/	private synchronized java.sql.Connection getValidConnection() throws Exception	{		boolean hasPrint = false;		// If there is no pool it must have been destroyed		if (pool == null)		{			return null;		}				java.sql.Connection con = null;		PooledConnection pooledCon = null;				int poolSize = pool.size();		// Get the next available connection		for (int i = 0; i < poolSize; i++)		{					// Get the PooledConnection from the pool			PooledConnection pc = (PooledConnection)pool.elementAt(i);						// If this is a valid connection and it is not in use,			// grab it			if (pc.isAvailable())			{				pooledCon = pc;				break;			}		}				// No more available connections. If we aren't at the		// maximum number of connections, create a new entry		// in the pool		if (null == pooledCon )		{			if ((connectionPoolMax < 0) ||((connectionPoolMax > 0) &&(poolSize < connectionPoolMax)))			{							// Add a new connection.				int i = addConnection();								// If a new connection was created, use it				if (i >= 0)				{					pooledCon = (PooledConnection)pool.elementAt(i);				}			}			else			{				if( !hasPrint )				{					//System.out.println("池内连接数达到上限");					hasPrint = true;              				}			}		}		// If we have a connection, set the last time accessed,		// the use count, and the in use flag		if (pooledCon != null)		{			pooledCon.inUse = true;			pooledCon.useCount++;			touch(pooledCon);			con = pooledCon.con;			//System.out.println( "分配连接:"+pooledCon.getTimeTagID() );		}		return con;	}		/**	* <p>Places the connection back into the connection pool,	* or closes the connection if the maximum use count has	* been reached	*	* @param con Connection object to close	*/	public synchronized void close(java.sql.Connection con)	{		// Find the connection in the pool		int index = find(con);				if (index != -1)		{			PooledConnection pc = (PooledConnection)pool.elementAt(index);					// If the use count exceeds the max, remove it from			// the pool.			if ((connectionUseCount > 0) &&			    (pc.useCount >= connectionUseCount))			{				//System.out.println( "连接的使用次数达到上限:"+pc.getTimeTagID() );				removeFromPool(index);			}			else			{				// Clear the use count and reset the time last used				touch(pc);				pc.inUse = false;			}		}	}		/**	* <p>Prints the contents of the connection pool to the	* standard output device	*/	public void printPool()	{		//System.out.println("--ConnectionPool--");		if (pool != null)		{			for (int i = 0; i < pool.size(); i++)			{				PooledConnection pc = (PooledConnection)pool.elementAt(i);				//System.out.println("" + i + "=" + pc.toString());			}		}	}		/**	* <p>Removes the PooledConnection from the pool at the	* given index	*	* @param index Index into the pool vector	*/	private synchronized void removeFromPool(int index)	{		// Make sure the pool and index are valid		//System.out.println( "当前池大小="+pool.size() );		if (pool != null)		{					if (index < pool.size())			{							// Get the PooledConnection and close the connection				PooledConnection pc = (PooledConnection)pool.elementAt(index);				close(pc);								// Remove the element from the pool				pool.removeElementAt(index);				//System.out.println( "删除连接:"+pc.getTimeTagID() );			}		}	}		/**	* <p>Closes the connection in the given PooledConnection	*	* @param connectObject PooledConnection

⌨️ 快捷键说明

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