1
0

CDBConnPool.cpp 9.0 KB

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