CDBConnPool.cpp 8.3 KB

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