#include "../pch/pch.h" #include "DBPool.h" DBPool::DBPool() { } DBPool::~DBPool() { this->DestoryConnPool(); } void DBPool::InitPool() { this->database = CConfigReader::getDBName(); this->user = CConfigReader::getMysqlUsername(); this->password = CConfigReader::getMysqlPassword(); this->url = CConfigReader::getMysqlHost(); this->maxSize = MAX_DB_CONNECTION_NUM; this->curSize = 0; try { this->driver = sql::mysql::get_driver_instance(); } catch (sql::SQLException& e) { LOG_INFO("SQLException:" << e.what()); cout<<"SQLException:" << e.what()<InitConnection(maxSize / 2); } void DBPool::InitConnection(int initSize) { Connection* conn; std::lock_guard guard(m_mutex); for (int i = 0; i < initSize; i++) { conn = this->CreateConnection(); if (conn) { //cout << "connect mysql success" << endl; connList.push_back(conn); ++(this->curSize); } else { LOG_INFO("create conn error"); //cout << "create conn error" << endl; } } } Connection* DBPool::CreateConnection() { Connection* conn; try { conn = driver->connect(this->url.c_str(), this->user.c_str(), this->password.c_str()); //create a conn conn->setSchema(this->database.c_str()); return conn; } catch (sql::SQLException& e) { LOG_INFO("SQLException:" << e.what()); //cout << "SQLException:" << e.what() << endl; return NULL; } catch (std::runtime_error& e) { LOG_INFO("SQLException:" << e.what()); //cout << "SQLException:" << e.what() << endl; return NULL; } } Connection* DBPool::GetConnection() { Connection* conn; std::lock_guard guard(m_mutex); if (connList.size() > 0)//the pool have a conn { conn = connList.front(); connList.pop_front();//move the first conn if (conn->isClosed() || conn->isValid() == false) { //如果连接已经不可用,重新建立一个连接 if (conn->isClosed() == false) { conn->close(); } delete conn; conn = this->CreateConnection(); if (conn == NULL) { LOG_INFO("new conn is null!"); --curSize; } } //这里直接返回连接,不能加入池子,等用完了会通过ReleaseConnection加入池子 return conn; } else { if (curSize < maxSize)//the pool no conn { conn = this->CreateConnection(); if (conn) { ++curSize; return conn; } else { return NULL; } } else //the conn count > maxSize { //连接池已经达到最大数量了 return NULL; } } } //put conn back to pool void DBPool::ReleaseConnection(Connection *conn) { if (conn) { std::lock_guard guard(m_mutex); connList.push_back(conn); } } void DBPool::DestoryConnPool() { list::iterator iter; std::lock_guard guard(m_mutex); for (iter = connList.begin(); iter != connList.end(); ++iter) { this->DestoryConnection(*iter); } curSize = 0; connList.clear(); } void DBPool::DestoryConnection(Connection* conn) { if (conn) { try { conn->close(); } catch (sql::SQLException&e) { perror(e.what()); } catch (std::exception& e) { perror(e.what()); } delete conn; } }