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

📄 pooledconnectionmgr.java

📁 本人课程设计时做的一个用struts框架实现的基于cmmi2的项目管理系统的原型。还有部分功能尚未实现
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
	*/	private void close(PooledConnection pooledCon)	{		if (pooledCon != null)		{			//System.out.println( "关闭连接:"+pooledCon.getTimeTagID() );			if (pooledCon.con != null)			{				try				{		    					// Close the connection					pooledCon.con.close();				}				catch (Exception ex)				{					// Ignore any exceptions during close				}								// Clear the connection object reference				pooledCon.con = null;			}		}	}		/**	* <p>Creates the initial connection pool. A timer thread	* is also created so that connection timeouts can be	* handled.	*	* @return true if the pool was created	*/	private void createPool() throws Exception	{		// Sanity check our properties		if (JDBCDriver == null)		{			//System.out.println( "JDBCDriver 未初始化" );			throw new Exception("JDBCDriver property not found");		}		if (JDBCConnectionURL == null)		{			//System.out.println( "JDBCConnectionURL 未初始化" );			throw new Exception("JDBCConnectionURL property not found");		}		if (connectionPoolSize < 0)		{			//System.out.println( "ConnectionPoolSize 未初始化" );			throw new Exception("ConnectionPoolSize property not found");		}		if (connectionPoolSize == 0)		{			//System.out.println( "ConnectionPoolSize 非法" );			throw new Exception("ConnectionPoolSize invalid");		}		if (connectionPoolMax < connectionPoolSize)		{			//System.out.println( "最大连接数非法,将被忽略" );			connectionPoolMax = -1;		}		if (connectionTimeout < 0)		{			// Set the default to 30 minutes			connectionTimeout = 30;		}				//System.out.println("JDBCDriver = " + JDBCDriver);		//System.out.println("JDBCConnectionURL = " + JDBCConnectionURL);		//System.out.println("ConnectionPoolSize = " + connectionPoolSize);		//System.out.println("ConnectionPoolMax = " + connectionPoolMax);		//System.out.println("ConnectionUseCount = " + connectionUseCount);		//System.out.println("ConnectionTimeout = " + connectionTimeout +" seconds");				// Attempt to create a new instance of the specified		// JDBC driver. Well behaved drivers will register		// themselves with the JDBC DriverManager when they		// are instantiated		//System.out.println("Registering " + JDBCDriver);		java.sql.Driver d = (java.sql.Driver)		Class.forName(JDBCDriver).newInstance();		// Create the vector for the pool		pool = new java.util.Vector();				// Bring the pool to the minimum size		fillPool(connectionPoolSize);	}			/**	* <p>Adds a new connection to the pool	*	* @return Index of the new pool entry, or -1 if an	* error has occurred	*/	private int addConnection() throws Exception	{		int index = -1;				try		{			// Calculate the new size of the pool			int size = pool.size() + 1;						// Create a new entry			fillPool(size);						// Set the index pointer to the new connection if one			// was created			if (size == pool.size())			{				index = size - 1;			}		}		catch (Exception ex)		{			throw new Exception(ex);		}		return index;	}		/**	* <p>Brings the pool to the given size	* @throws Exception	*/	private synchronized void fillPool(int size) throws Exception	{		//System.out.println( "填充连接池开始" );		while (pool.size() < size)		{			PooledConnection pc = new PooledConnection();  			pc.con = DriverManager.getConnection( JDBCConnectionURL,			                                      userName,			                                      passWord);			// Do some sanity checking on the first connection in			// the pool			if (pool.size() == 0)			{							// Get the maximum number of simultaneous connections				// as reported by the JDBC driver				java.sql.DatabaseMetaData md = pc.con.getMetaData();				maxConnections = md.getMaxConnections();			}						// Give a warning if the size of the pool will exceed			// the maximum number of connections allowed by the			// JDBC driver			if ((maxConnections > 0) &&			    (size > maxConnections))			{				//System.out.println("警告: 连接池已达到安全的上限 " + maxConnections);			}						// Clear the in use flag			pc.inUse = false;						// Set the last access time			touch(pc);			pool.addElement(pc);			//System.out.println( "增加连接:"+pc.getTimeTagID() );		}		//System.out.println( "填充连接池结束   当前池的大小="+pool.size() );	}		/**	* <p>Find the given connection in the pool	*	* @return Index into the pool, or -1 if not found	*/	private int find(java.sql.Connection con)	{		int index = -1;				// Find the matching Connection in the pool		if ((con != null) &&(pool != null))		{			for (int i = 0; i < pool.size(); i++)			{				PooledConnection pc = (PooledConnection)pool.elementAt(i);				if (pc.con == con)				{					index = i;					break;				}			}		}		return index;	}		/**	* <p>Called by the timer each time a clock cycle expires.	* This gives us the opportunity to timeout connections	*/	public synchronized void TimerEvent(Object object)	{		//System.out.println( "定时检查开始" );		// No pool means no work		if (pool == null)		{			//System.out.println("The pool is empty!!!");			return;		}				// Get the current time in milliseconds		long now = System.currentTimeMillis();				// Check for any expired connections and remove them		for (int i = pool.size() - 1; i >= 0; i--)		{			PooledConnection pc = (PooledConnection)pool.elementAt(i);						// If the connection is not in use and it has not been			// used recently, remove it			if (!pc.inUse)			{				if ((connectionTimeout > 0) &&(pc.lastAccess +(connectionTimeout * 1000) < now))				{					//System.out.println( "连接超时,即将关闭:"+pc.getTimeTagID() );					removeFromPool(i);				}			}		}				// Remove any connections that are no longer open		for (int i = pool.size() - 1; i >= 0; i--)		{			PooledConnection pc = (PooledConnection)pool.elementAt(i);			try			{				// If the connection is closed, remove it from the pool				if (pc.con.isClosed())				{					//System.out.println("连接异常关闭:"+pc.getTimeTagID());					removeFromPool(i);				}			}			catch (Exception ex)			{			}		}				// Now ensure that the pool is still at it's minimum size		try		{			if (pool != null)			{				if (pool.size() < connectionPoolSize)				{					fillPool(connectionPoolSize);				}			}		}		catch (Exception ex)		{			ex.printStackTrace();		}		//System.out.println( "定时检查结束" );	}		/**	* <p>Sets the last access time for the given PooledConnection	*/	private void touch(PooledConnection pc)	{		if (pc != null)		{			pc.lastAccess = System.currentTimeMillis();		}	}		/*	* <p>System.out.println the given string	*    At present the log infromation has been printed in the console.	*	private void System.out.println(String s)	{		//logFile.writeLog( s );		System.out.println(s);	}		public static void main(String[] args)	{		try		{			PooledConnectionMgr pool = PooledConnectionMgr.getInstance();			pool.setJDBCDriver( "org.gjt.mm.mysql.Driver" );			pool.setJDBCConnectionURL( "jdbc:mysql://192.168.15.150:3306/CMMI2PM" );			pool.setConnectionPoolSize( 5 );			pool.setConnectionPoolMax( 10 );			pool.setConnectionUseCount( 8 );			pool.setConnectionTimeout( 30 );						pool.initialize(30);					Connection con= pool.getConnection();			Statement s = con.createStatement();			ResultSet rs = s.executeQuery("SELECT * FROM user ");			System.out.println("ID\tusername\tfull_name\tpassword");			while(rs.next())			{				System.out.println(rs.getString(1)+"\t"+rs.getString(2)+"\t\t"+rs.getString(3)+"\t"+rs.getString(4));			}			System.out.println("--------end--------");			s.close();			pool.printPool();			pool.close( con );						pool.destroy();		}		catch (Exception e)		{			e.printStackTrace();		}	}	*/	public java.sql.Connection getConnection() throws Exception	{		java.util.Date d = new java.util.Date();		java.sql.Connection con = null;		long enterTime = (long) d.getTime();		while( con==null )		{			long curTime = (long) d.getTime();			if( curTime-enterTime > waitTimeOut*1000 )			{				throw new Exception("系统忙,请稍后重试!");			}			con = getValidConnection();			if( con == null)			{				synchronized( d )				{					try					{						wait(20);					}					catch( InterruptedException e ){}    	     				}			}		   		}		return con;	}	}

⌨️ 快捷键说明

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