CDBConnPool.cpp 8.4 KB

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