CDBConnPool.cpp 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. #include "CDBConnPool.h"
  2. #include <boost/bind.hpp>
  3. namespace YADB
  4. {
  5. boost::lockfree::queue<_ASYNC_SQL_*, boost::lockfree::capacity<MAX_ASYNC_QUEQUE_CAPACITY>> __AsyncQueue;//异步执行无锁队列
  6. CDBConnPool::CDBConnPool()
  7. {
  8. __pAsyncDBConn = 0;
  9. }
  10. CDBConnPool::~CDBConnPool()
  11. {
  12. Close();
  13. }
  14. CDBConnect * CDBConnPool::__CreateIdleConn( std::string& ConnErr, bool IsTemp )
  15. {
  16. //std::string ConnErr;
  17. _DB_CONN_SETTING_ ConnSetting = static_cast< _DB_CONN_SETTING_ >(__Setting);
  18. CDBConnect* pConn = new CDBConnect( IsTemp );
  19. if ( !pConn->Connect( ConnSetting, ConnErr ) )
  20. {
  21. delete pConn;
  22. pConn = 0;
  23. return 0;
  24. }
  25. //如果设置了预处理SQL要准备预处理
  26. if ( !ConnSetting.stmtSQL.empty() )
  27. {
  28. if ( !pConn->Preparestmt( ConnSetting.stmtSQL.c_str(), ConnErr ) )
  29. {
  30. delete pConn;
  31. pConn = 0;
  32. return 0;
  33. }
  34. }
  35. __IdleConnList.push_back( pConn );
  36. return pConn;
  37. }
  38. bool CDBConnPool::Create( const _DB_POOL_SETTING_& Setting, std::string& szError )
  39. {
  40. return Create(Setting,true,szError);
  41. }
  42. bool CDBConnPool::Create( const _DB_POOL_SETTING_& Setting,bool bAsync, std::string& szError )
  43. {
  44. std::unique_lock<std::mutex> lock( __mtx );
  45. if ( Setting.PoolSize < DCC_MIN_COUNT )
  46. {
  47. szError = "PoolSize is too small!";
  48. return false;
  49. }
  50. if ( Setting.PoolSize > DCC_MAX_COUNT )
  51. {
  52. szError = "PoolSize is too big!";
  53. return false;
  54. }
  55. __Setting = Setting;
  56. //检查连接池中是否已有连接数量
  57. if ((int)__IdleConnList.size() < __Setting.PoolSize)
  58. {
  59. for ( int i = 0; i < __Setting.PoolSize; i++ )
  60. {
  61. CDBConnect* pConn = __CreateIdleConn( szError );
  62. if ( !pConn )
  63. {
  64. return false;
  65. }
  66. }
  67. }
  68. // 是否已创建异步线程
  69. if (bAsync || !__Running)
  70. {
  71. //创建异步执行线程
  72. __CreateAsyncThrdConn();
  73. //启动异步执行线程
  74. __StartAsyncThrd();
  75. }
  76. return true;
  77. }
  78. void CDBConnPool::Close()
  79. {
  80. std::unique_lock<std::mutex> lock( __mtx );
  81. //停止异步执行线程
  82. __StopAsyncThrd();
  83. //刪除异步执行线程连接
  84. __DestroyAsyncThrdConn();
  85. //把所有列表中的连接对象都关闭删除并清除列表
  86. CDBConnect* pConn = 0;
  87. std::list<CDBConnect*>::iterator lit_conn;
  88. for ( lit_conn = __BusyConnList.begin(); lit_conn != __BusyConnList.end(); lit_conn++ )
  89. {
  90. pConn = *lit_conn;
  91. pConn->Close();
  92. delete pConn;
  93. pConn = 0;
  94. }
  95. __BusyConnList.clear();
  96. for ( lit_conn = __IdleConnList.begin(); lit_conn != __IdleConnList.end(); lit_conn++ )
  97. {
  98. pConn = *lit_conn;
  99. pConn->Close();
  100. delete pConn;
  101. pConn = 0;
  102. }
  103. __IdleConnList.clear();
  104. }
  105. CDBConnect * CDBConnPool::GetDBConnect( std::string& Error )
  106. {
  107. std::unique_lock<std::mutex> lock( __mtx );
  108. CDBConnect* pConn = 0;
  109. if ( __IdleConnList.size() > 0 )
  110. {
  111. pConn = *(__IdleConnList.begin());
  112. __IdleConnList.pop_front();
  113. __BusyConnList.push_back( pConn );
  114. }
  115. else
  116. {
  117. //如果已经没有空闲连接,只要当前连接池数量没有超过最大连接数就创建一个临时连接
  118. // 这个判断没有意义(进入这个 __IdleConnList.size() <= 0 )
  119. if ( __IdleConnList.size() < DCC_MAX_COUNT )
  120. {
  121. pConn = __CreateIdleConn( Error, true );
  122. if ( !pConn )
  123. {
  124. Error = "Error,failed connect to database!";
  125. return 0;
  126. }
  127. __IdleConnList.pop_front();
  128. __BusyConnList.push_back( pConn );
  129. }
  130. else
  131. {
  132. Error = "Error,db connect count beyond the max connect count!";
  133. return 0;
  134. }
  135. }
  136. //验证看数据库连接是否还有效
  137. if ( pConn )
  138. {
  139. if ( pConn->ConnctionTest( Error ) != 0 )
  140. {
  141. //重连一次
  142. _DB_CONN_SETTING_ ConnSetting = static_cast< _DB_CONN_SETTING_ >(__Setting);
  143. pConn->Close();
  144. int nRet = pConn->Connect( ConnSetting, Error );
  145. if ( nRet < 0 )
  146. {
  147. GiveBack( pConn );
  148. Error = "Error,failed connect to database!";
  149. return 0;
  150. }
  151. }
  152. }
  153. return pConn;
  154. }
  155. void CDBConnPool::GiveBack( CDBConnect * pConn )
  156. {
  157. std::unique_lock<std::mutex> lock( __mtx );
  158. if ( 0 == pConn )
  159. {
  160. return;
  161. }
  162. __BusyConnList.remove( pConn );
  163. //如果是临时连接,直接删除不再放入到空闲连接列表中
  164. if ( pConn->IsTemp() )
  165. {
  166. delete pConn;
  167. pConn = 0;
  168. }
  169. else
  170. {
  171. __IdleConnList.push_back( pConn );
  172. }
  173. }
  174. void CDBConnPool::_AsyncThreadFunc( CDBConnPool* pOwner )
  175. {
  176. std::string Error;
  177. while( pOwner->__Running )
  178. {
  179. _ASYNC_SQL_* pData = 0;
  180. while ( __AsyncQueue.pop( pData ) )
  181. {
  182. if ( pData )
  183. {
  184. if ( __pAsyncDBConn )
  185. {
  186. my_ulonglong llRes = 0;
  187. llRes = __pAsyncDBConn->ExecuteRealSql( pData->SQL.c_str(), Error );
  188. if ( (my_ulonglong)-1 == llRes )
  189. {
  190. //Execute failed, write log...
  191. printf( "Error,调用ExcuteRealSql失败,Err=%s \n sql=%s \n", Error.c_str(), pData->SQL.c_str());
  192. //如果失败了看是不是数据库断开连接了,尝试重新连接一次
  193. if ( __pAsyncDBConn->ConnctionTest( Error ) != 0 )
  194. {
  195. _DB_CONN_SETTING_ ConnSetting = static_cast< _DB_CONN_SETTING_ >(__Setting);
  196. __pAsyncDBConn->Close();
  197. int nRet = __pAsyncDBConn->Connect( ConnSetting, Error );
  198. if ( nRet < 0 )
  199. {
  200. Error = "Error,failed connect to database!";
  201. //Connect failed, write log...
  202. printf( "Error,failed connect to database,Err=%s\n", Error.c_str() );
  203. //如果连接失败了休息一下
  204. boost::this_thread::sleep( boost::posix_time::milliseconds( 100 ) );
  205. }
  206. }
  207. //如果执行失败,失败次数加一,失败次数小于最大失败次数放到队尾下次再执行
  208. pData->FailedCount++;
  209. if ( pData->FailedCount < MAX_ASYNC_EXEC_FAILED_COUNT )
  210. {
  211. _ASYNC_SQL_* pNewData = new _ASYNC_SQL_();
  212. pNewData->FailedCount = pData->FailedCount;
  213. pNewData->SQL = pData->SQL;
  214. __AsyncQueue.push( pNewData );
  215. }
  216. }
  217. }
  218. delete pData;
  219. pData = 0;
  220. }
  221. }
  222. boost::this_thread::sleep( boost::posix_time::microseconds( 10 ) );
  223. }
  224. //线程退出
  225. __IsExited = true;
  226. }
  227. void CDBConnPool::__StopAsyncThrd()
  228. {
  229. if ( !__Running )
  230. {
  231. return;
  232. }
  233. //等待异步执行线程退出
  234. __Running = false;
  235. while ( !__IsExited )
  236. {
  237. boost::this_thread::sleep(boost::posix_time::millisec(1));
  238. }
  239. //把异步执行无锁队列中每个元素释放
  240. _ASYNC_SQL_* pData = 0;
  241. while ( __AsyncQueue.pop( pData ) )
  242. {
  243. if (pData)
  244. {
  245. delete pData;
  246. pData = 0;
  247. }
  248. }
  249. }
  250. void CDBConnPool::__StartAsyncThrd()
  251. {
  252. __Running = true;
  253. boost::thread thrd( boost::bind( &CDBConnPool::_AsyncThreadFunc, this, this ) );
  254. thrd.detach();
  255. }
  256. void CDBConnPool::__CreateAsyncThrdConn()
  257. {
  258. std::string ConnErr;
  259. //先断开之前的连接
  260. this->__DestroyAsyncThrdConn();
  261. _DB_CONN_SETTING_ ConnSetting = static_cast< _DB_CONN_SETTING_ >(__Setting);
  262. CDBConnect* pConn = new CDBConnect();
  263. if ( !pConn->Connect( ConnSetting, ConnErr ) )
  264. {
  265. delete pConn;
  266. pConn = 0;
  267. return;
  268. }
  269. __pAsyncDBConn = pConn;
  270. }
  271. void CDBConnPool::__DestroyAsyncThrdConn()
  272. {
  273. if ( __pAsyncDBConn )
  274. {
  275. __pAsyncDBConn->Close();
  276. delete __pAsyncDBConn;
  277. __pAsyncDBConn = 0;
  278. }
  279. }
  280. bool CDBConnPool::PushAsync( const std::string& strSQL )
  281. {
  282. _ASYNC_SQL_* pData = new _ASYNC_SQL_;
  283. if ( !pData )
  284. {
  285. return false;
  286. }
  287. pData->SQL = strSQL;
  288. return __AsyncQueue.push( pData );
  289. }
  290. bool CDBConnPool::Query( const char *szSql, CDBResultSet& DBRes,std::string& Error )
  291. {
  292. CDBConnect *pConn = GetDBConnect( Error );
  293. if ( 0 == pConn )
  294. {
  295. return false;
  296. }
  297. MYSQL_RES* pRes = pConn->Query( szSql, Error );
  298. GiveBack( pConn );
  299. return DBRes.Bind( pRes, Error );
  300. }
  301. MYSQL_RES* CDBConnPool::Query( const char *szSql, std::string& Error)
  302. {
  303. CDBConnect *pConn = GetDBConnect(Error);
  304. if( 0 == pConn){
  305. return nullptr;
  306. }
  307. MYSQL_RES* pRes = pConn->Query(szSql,Error);
  308. GiveBack(pConn);
  309. return pRes;
  310. }
  311. my_ulonglong CDBConnPool::ExecuteSql( const char *szSql, std::string& Error )
  312. {
  313. CDBConnect *pConn = GetDBConnect( Error );
  314. if ( 0 == pConn )
  315. {
  316. return -1;
  317. }
  318. my_ulonglong nRet = pConn->ExecuteSql( szSql, Error );
  319. GiveBack( pConn );
  320. return nRet;
  321. //return pConn->ExecuteSql( szSql, Error );
  322. }
  323. }