1
0

CDBConnPool.cpp 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. #include "CDBConnPool.h"
  2. #include <boost/bind.hpp>
  3. #include <thread>
  4. #include <log.h>
  5. namespace YADB
  6. {
  7. // boost::lockfree::queue<_ASYNC_SQL_*, boost::lockfree::capacity<32768>> __AsyncQueue;//异步执行无锁队列
  8. std::mutex g_mutex;
  9. std::vector<_ASYNC_SQL_*> g_sql_list;
  10. CDBConnPool::CDBConnPool()
  11. {
  12. g_sql_list.reserve(1<<15);
  13. __pAsyncDBConn = 0;
  14. }
  15. CDBConnPool::~CDBConnPool()
  16. {
  17. Close();
  18. }
  19. CDBConnect * CDBConnPool::__CreateIdleConn( std::string& ConnErr, bool IsTemp )
  20. {
  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. //uint64_t cc=0;
  222. while( pOwner->__Running )
  223. {
  224. if(!g_sql_list.empty()){
  225. std::vector<_ASYNC_SQL_*> sql_list;
  226. sql_list.reserve(1<<15);
  227. {
  228. std::unique_lock<std::mutex> lock(g_mutex);
  229. sql_list.swap(g_sql_list);
  230. }
  231. //100ms太理想了。上下井高峰期这个有可能1h都没一条日志
  232. //if(++cc % 100 == 0)//100ms 输出一次
  233. logn_info(2,"sql_list size=%lld", sql_list.size());
  234. //1条链接处理sql。sql堆积。速度慢
  235. for(auto pData:sql_list)
  236. ExecAsyncSql(pData);
  237. }
  238. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  239. }
  240. //线程退出
  241. __IsExited = true;
  242. }
  243. void CDBConnPool::__StopAsyncThrd()
  244. {
  245. if ( !__Running )
  246. {
  247. return;
  248. }
  249. //等待异步执行线程退出
  250. __Running = false;
  251. while ( !__IsExited )
  252. {
  253. boost::this_thread::sleep(boost::posix_time::millisec(1));
  254. }
  255. //把异步执行无锁队列中每个元素释放
  256. {
  257. std::unique_lock<std::mutex> lock( g_mutex );
  258. std::for_each(g_sql_list.begin(),g_sql_list.end(),[](_ASYNC_SQL_*psql){
  259. delete psql;
  260. });
  261. g_sql_list.clear();
  262. #if 0
  263. _ASYNC_SQL_* pData = 0;
  264. while ( __AsyncQueue.pop( pData ) )
  265. {
  266. if (pData)
  267. {
  268. delete pData;
  269. pData = 0;
  270. }
  271. }
  272. #endif
  273. }
  274. }
  275. void CDBConnPool::__StartAsyncThrd()
  276. {
  277. __Running = true;
  278. boost::thread thrd( boost::bind( &CDBConnPool::_AsyncThreadFunc, this, this ) );
  279. thrd.detach();
  280. }
  281. void CDBConnPool::__CreateAsyncThrdConn()
  282. {
  283. std::string ConnErr;
  284. //先断开之前的连接
  285. this->__DestroyAsyncThrdConn();
  286. _DB_CONN_SETTING_ ConnSetting = static_cast< _DB_CONN_SETTING_ >(__Setting);
  287. CDBConnect* pConn = new CDBConnect();
  288. if ( !pConn->Connect( ConnSetting, ConnErr ) )
  289. {
  290. delete pConn;
  291. pConn = 0;
  292. return;
  293. }
  294. __pAsyncDBConn = pConn;
  295. }
  296. void CDBConnPool::__DestroyAsyncThrdConn()
  297. {
  298. if ( __pAsyncDBConn )
  299. {
  300. __pAsyncDBConn->Close();
  301. delete __pAsyncDBConn;
  302. __pAsyncDBConn = 0;
  303. }
  304. }
  305. bool CDBConnPool::PushAsync( std::string&& strSQL )
  306. {
  307. std::unique_lock<std::mutex> lock(g_mutex);
  308. g_sql_list.push_back(new _ASYNC_SQL_(std::move(strSQL)));
  309. return true;
  310. }
  311. bool CDBConnPool::Query( const char *szSql, CDBResultSet& DBRes,std::string& Error )
  312. {
  313. CDBConnect *pConn = GetDBConnect( Error );
  314. if ( 0 == pConn )
  315. {
  316. return false;
  317. }
  318. MYSQL_RES* pRes = pConn->Query( szSql, Error );
  319. GiveBack( pConn );
  320. return DBRes.Bind( pRes, Error );
  321. }
  322. MYSQL_RES* CDBConnPool::Query( const char *szSql, std::string& Error)
  323. {
  324. CDBConnect *pConn = GetDBConnect(Error);
  325. if( 0 == pConn){
  326. return nullptr;
  327. }
  328. MYSQL_RES* pRes = pConn->Query(szSql,Error);
  329. GiveBack(pConn);
  330. return pRes;
  331. }
  332. my_ulonglong CDBConnPool::ExecuteSql( const char *szSql, std::string& Error )
  333. {
  334. CDBConnect *pConn = GetDBConnect( Error );
  335. if ( 0 == pConn )
  336. {
  337. return -1;
  338. }
  339. my_ulonglong nRet = pConn->ExecuteSql( szSql, Error );
  340. GiveBack( pConn );
  341. return nRet;
  342. //return pConn->ExecuteSql( szSql, Error );
  343. }
  344. my_ulonglong CDBConnPool::ExecuteSqlID( const char * szSql, std::string & Error )
  345. {
  346. CDBConnect *pConn = GetDBConnect( Error );
  347. if ( 0 == pConn )
  348. {
  349. return -1;
  350. }
  351. my_ulonglong nRet = pConn->ExecuteSqlID( szSql, Error );
  352. GiveBack( pConn );
  353. return nRet;
  354. }
  355. }