CDBConnPool.cpp 8.1 KB

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