CDBConnPool.cpp 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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(); //zzj, ERROR!!,应该是pop_back吧
  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. //验证看数据库连接是否还有效 //zzj, 新建的链接不需要测试
  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. //zzj, 建议使用栈展开的方式 自动回收
  151. void CDBConnPool::GiveBack( CDBConnect * pConn )
  152. {
  153. std::unique_lock<std::mutex> lock( __mtx );
  154. if ( 0 == pConn )
  155. {
  156. return;
  157. }
  158. __BusyConnList.remove( pConn );
  159. //如果是临时连接,直接删除不再放入到空闲连接列表中
  160. if ( pConn->IsTemp() )
  161. {
  162. delete pConn;
  163. pConn = 0;
  164. }
  165. else
  166. {
  167. __IdleConnList.push_back( pConn );
  168. }
  169. }
  170. void CDBConnPool::_AsyncThreadFunc( CDBConnPool* pOwner )
  171. {
  172. std::string Error;
  173. while( pOwner->__Running )
  174. {
  175. _ASYNC_SQL_* pData = 0;
  176. while ( __AsyncQueue.pop( pData ) )
  177. {
  178. if ( pData )
  179. {
  180. if ( __pAsyncDBConn )
  181. {
  182. my_ulonglong llRes = 0;
  183. llRes = __pAsyncDBConn->ExecuteRealSql( pData->SQL.c_str(), Error );
  184. if ( (my_ulonglong)-1 == llRes )
  185. {
  186. //Execute failed, write log...
  187. printf( "Error,调用ExcuteRealSql失败,Err=%s \n sql=%s \n", Error.c_str(), pData->SQL.c_str());
  188. //如果失败了看是不是数据库断开连接了,尝试重新连接一次
  189. if ( __pAsyncDBConn->ConnctionTest( Error ) != 0 )
  190. {
  191. _DB_CONN_SETTING_ ConnSetting = static_cast< _DB_CONN_SETTING_ >(__Setting);
  192. __pAsyncDBConn->Close();
  193. int nRet = __pAsyncDBConn->Connect( ConnSetting, Error );
  194. if ( nRet < 0 )
  195. {
  196. Error = "Error,failed connect to database!";
  197. //Connect failed, write log...
  198. printf( "Error,failed connect to database,Err=%s\n", Error.c_str() );
  199. //如果连接失败了休息一下
  200. boost::this_thread::sleep( boost::posix_time::milliseconds( 100 ) );
  201. }
  202. }
  203. //如果执行失败,失败次数加一,失败次数小于最大失败次数放到队尾下次再执行
  204. pData->FailedCount++;
  205. if ( pData->FailedCount < MAX_ASYNC_EXEC_FAILED_COUNT )
  206. {
  207. _ASYNC_SQL_* pNewData = new _ASYNC_SQL_();
  208. pNewData->FailedCount = pData->FailedCount;
  209. pNewData->SQL = pData->SQL;
  210. __AsyncQueue.push( pNewData );
  211. }
  212. }
  213. }
  214. delete pData;
  215. pData = 0;
  216. }
  217. }
  218. boost::this_thread::sleep( boost::posix_time::microseconds( 10 ) );
  219. }
  220. //线程退出
  221. __IsExited = true;
  222. }
  223. void CDBConnPool::__StopAsyncThrd()
  224. {
  225. if ( !__Running )
  226. {
  227. return;
  228. }
  229. //等待异步执行线程退出
  230. __Running = false;
  231. while ( !__IsExited )
  232. {
  233. boost::this_thread::sleep(boost::posix_time::millisec(1));
  234. }
  235. //把异步执行无锁队列中每个元素释放
  236. _ASYNC_SQL_* pData = 0;
  237. while ( __AsyncQueue.pop( pData ) )
  238. {
  239. if (pData)
  240. {
  241. delete pData;
  242. pData = 0;
  243. }
  244. }
  245. }
  246. void CDBConnPool::__StartAsyncThrd()
  247. {
  248. boost::thread thrd( boost::bind( &CDBConnPool::_AsyncThreadFunc, this, this ) );
  249. thrd.detach();
  250. }
  251. void CDBConnPool::__CreateAsyncThrdConn()
  252. {
  253. std::string ConnErr;
  254. _DB_CONN_SETTING_ ConnSetting = static_cast< _DB_CONN_SETTING_ >(__Setting);
  255. CDBConnect* pConn = new CDBConnect();
  256. if ( !pConn->Connect( ConnSetting, ConnErr ) )
  257. {
  258. delete pConn;
  259. pConn = 0;
  260. return;
  261. }
  262. __pAsyncDBConn = pConn;
  263. }
  264. void CDBConnPool::__DestroyAsyncThrdConn()
  265. {
  266. if ( __pAsyncDBConn )
  267. {
  268. __pAsyncDBConn->Close();
  269. delete __pAsyncDBConn;
  270. __pAsyncDBConn = 0;
  271. }
  272. }
  273. bool CDBConnPool::PushAsync( const std::string& strSQL )
  274. {
  275. _ASYNC_SQL_* pData = new _ASYNC_SQL_;
  276. if ( !pData )
  277. {
  278. return false;
  279. }
  280. pData->SQL = strSQL;
  281. return __AsyncQueue.push( pData );
  282. }
  283. bool CDBConnPool::Query( const char *szSql, CDBResultSet& DBRes,std::string& Error )
  284. {
  285. CDBConnect *pConn = GetDBConnect( Error );
  286. if ( 0 == pConn )
  287. {
  288. return false;
  289. }
  290. MYSQL_RES* pRes = pConn->Query( szSql, Error );
  291. GiveBack( pConn );
  292. return DBRes.Bind( pRes, Error );
  293. }
  294. MYSQL_RES* CDBConnPool::Query( const char *szSql, std::string& Error)
  295. {
  296. CDBConnect *pConn = GetDBConnect(Error);
  297. if( 0 == pConn){
  298. return nullptr;
  299. }
  300. MYSQL_RES* pRes = pConn->Query(szSql,Error);
  301. GiveBack(pConn);
  302. return pRes;
  303. }
  304. my_ulonglong CDBConnPool::ExecuteSql( const char *szSql, std::string& Error )
  305. {
  306. CDBConnect *pConn = GetDBConnect( Error );
  307. if ( 0 == pConn )
  308. {
  309. return -1;
  310. }
  311. my_ulonglong nRet = pConn->ExecuteSql( szSql, Error );
  312. GiveBack( pConn );
  313. return nRet;
  314. //return pConn->ExecuteSql( szSql, Error );
  315. }
  316. }