CDBConnPool.cpp 8.5 KB

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