CDBConnPool.cpp 8.7 KB

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