//刷新连接池中所有的连接对象
void MySQLConnectionPool::refreshConnections() {
	// 确保连接池己创新存在
	pthread_mutex_lock(&mutex_connectionpool);
	if (connections.empty()) {
		pthread_mutex_unlock(&mutex_connectionpool);
		return;
	}
	
	PooledConnection *pConn = NULL;
	
	for(int i =0 ; i<connections.size(); i++) {
		
		// 获得一个连接对象
		
		pConn = connections.at(i);
		
		// 如果对象忙则等 5 秒 ,5 秒后直接刷新
		
		if (pConn->isBusy()) {
			
			wait(5000); // 等 5 秒
			
		}
		
		// 关闭此连接,用一个新的连接代替它。
		
		closeConnection(pConn->getConnection());
		
		pConn->setConnection(newConnection());
		
		pConn->setBusy(false);
		
	}
	pthread_mutex_unlock(&mutex_connectionpool);
}
//查找连接池中所有的连接,查找一个可用的数据库连接
sql::Connection * MySQLConnectionPool::findFreeConnection() {
    sql::Connection * conn = NULL;
	
	PooledConnection *pConn = NULL;
	
	// 获得连接池向量中所有的对象
	for(int i = 0 ;i<connections.size(); i++) {
		
		pConn = connections.at(i);
		
		if (!pConn->isBusy()) {
			
			// 如果此对象不忙,则获得它的数据库连接并把它设为忙
			
			conn = pConn->getConnection();
			
			
			// 测试此连接是否可用
 			if (!testConnection(conn)) {
 				
 				// 如果此连接不可再用了,则创建一个新的连接,
 				
 				// 并替换此不可用的连接对象,如果创建失败,返回 null
 				
 				try {
 					conn = newConnection();
				} catch(...) {
 					return NULL;	
 				}
 				
				if (conn) {
 					pConn->setConnection(conn);	
					pConn->setBusy(true);
				} else {
					return NULL;
				}
			} else {
				pConn->setBusy(true);
			}
			break; // 己经找到一个可用的连接,退出	
		}	
	}
    //mysql_query( mysql, "SET NAMES" gbk"" );
    return conn;// 返回找到到的可用连接
}
ServClient* BloomfilterConnectionPool::findFreeConnection()
{
    ServClient * conn = NULL;
    PooledConnection *pConn = NULL;
    for(int i = 0 ;i<connections.size(); i++)
    {
        pConn = connections.at(i);
        if (!pConn->isBusy())
        {
            conn = pConn->getConnection();
            pConn->setBusy(true);
            break;
        }
    }

    return conn;
}
void BloomfilterConnectionPool::returnConnection(ServClient * conn)
{
    pthread_mutex_lock(&mutex_connectionpool);
    if (connections.empty())
    {
        pthread_mutex_unlock(&mutex_connectionpool);
        return;
    }

    PooledConnection* pConn = NULL;
    for (int i = 0; i < connections.size(); i++)
    {
        pConn = connections.at(i);

        if (conn == pConn->getConnection())
        {
            pConn->setBusy(false);
            break;
        }
    }
    pthread_mutex_unlock(&mutex_connectionpool);
}
//此函数返回一个数据库连接到连接池中,并把此连接置为空闲。
void MySQLConnectionPool::returnConnection(sql::Connection *conn) {
	pthread_mutex_lock(&mutex_connectionpool);
	if (connections.empty()) {
		pthread_mutex_unlock(&mutex_connectionpool);
		return;
	}
	
	PooledConnection *pConn = NULL;
	
	// 遍历连接池中的所有连接,找到这个要返回的连接对象
	for (int i= 0 ; i < connections.size() ; i++)
	{	
		pConn =connections.at(i);
		
		// 先找到连接池中的要返回的连接对象	
		if (conn == pConn->getConnection()) {
			
			// 找到了 , 设置此连接为空闲状态
			pConn->setBusy(false);
			break;	
		}		
	}
	pthread_mutex_unlock(&mutex_connectionpool);
}