ConnectionPool.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Configuration;
  5. using System.Data;
  6. using System.Data.SqlClient;
  7. using System.Diagnostics;
  8. using System.Text;
  9. namespace DateBaseConnection
  10. {
  11. public class ConnectionPool
  12. {
  13. private static ConnectionPool cpool = null;//池管理对象
  14. private static Object objlock = typeof(ConnectionPool);//池管理对象实例
  15. private int size = 10;//池中连接数
  16. private int useCount = 0;//已经使用的连接数
  17. private ArrayList pool = null;//连接保存的集合
  18. private Dictionary<string, SqlConnection> poolist = new Dictionary<string, SqlConnection>();
  19. private String ConnectionStr = "";//连接字符串
  20. public ConnectionPool()
  21. {
  22. //
  23. // TODO: 在此处添加构造函数逻辑
  24. //
  25. ConnectionStr = "server=127.0.0.1;database=Chloe;uid=sa;pwd=a1b2c3d4;Pooling=true;Max Pool Size=40000;Min Pool Size=0;";
  26. size = 100;
  27. pool = new ArrayList();
  28. }
  29. public SqlConnection getConn()
  30. {
  31. SqlConnection conn = new SqlConnection(ConnectionStr);
  32. return conn;
  33. }
  34. public static ConnectionPool getPools()
  35. {
  36. return new ConnectionPool();
  37. }
  38. //创建获取连接池对象
  39. public static ConnectionPool getPool()
  40. {
  41. lock (objlock)
  42. {
  43. if (cpool == null)
  44. {
  45. cpool = new ConnectionPool();
  46. }
  47. return cpool;
  48. }
  49. }
  50. //获取池中的连接
  51. public SqlConnection getConnection(string key)
  52. {
  53. lock (poolist)
  54. {
  55. SqlConnection tmp = null;
  56. if (poolist.ContainsKey(key))
  57. {
  58. tmp = poolist[key];
  59. poolist.Remove(key);
  60. //不成功
  61. if (!isUserful(tmp))
  62. {
  63. //可用的连接数据已去掉一个
  64. useCount--;
  65. tmp = getConnection(key);
  66. }
  67. }
  68. else
  69. {
  70. //可使用的连接小于连接数量
  71. if (useCount < size)
  72. {
  73. try
  74. {
  75. //创建连接
  76. SqlConnection conn = new SqlConnection(ConnectionStr);
  77. conn.Open();
  78. useCount++;
  79. tmp = conn;
  80. }
  81. catch (Exception e)
  82. {
  83. }
  84. }
  85. }
  86. return tmp;
  87. }
  88. }
  89. //关闭连接,加连接回到池中
  90. public void closeConnection(string key, SqlConnection con)
  91. {
  92. lock (poolist)
  93. {
  94. if (con != null)
  95. {
  96. if (poolist.ContainsKey(key))
  97. {
  98. poolist[key] = con;
  99. }
  100. else
  101. {
  102. poolist.Add(key, con);
  103. }
  104. }
  105. }
  106. }
  107. /// <summary>
  108. /// 关闭所有连接
  109. /// </summary>
  110. public void Close(string key)
  111. {
  112. lock (poolist)
  113. {
  114. if (poolist.ContainsKey(key))
  115. {
  116. SqlConnection con = poolist[key];
  117. con.Close();
  118. con.Dispose();
  119. }
  120. }
  121. }
  122. //目的保证所创连接成功,测试池中连接
  123. private bool isUserful(SqlConnection con)
  124. {
  125. //主要用于不同用户
  126. bool result = true;
  127. if (con != null)
  128. {
  129. string sql = "select 1";//随便执行对数据库操作
  130. SqlCommand cmd = new SqlCommand(sql, con);
  131. try
  132. {
  133. cmd.ExecuteScalar().ToString();
  134. }
  135. catch
  136. {
  137. result = false;
  138. }
  139. }
  140. return result;
  141. }
  142. /// <summary>
  143. /// 获取DataTable
  144. /// </summary>
  145. /// <param name="StrSql"></param>
  146. /// <returns></returns>
  147. public DataTable GetDataReader(string StrSql)//数据查询
  148. {
  149. SqlConnection SqlDrConn = new SqlConnection(ConnectionStr);
  150. //当连接处于打开状态时关闭,然后再打开,避免有时候数据不能及时更新
  151. if (SqlDrConn.State == ConnectionState.Open)
  152. {
  153. SqlDrConn.Close();
  154. }
  155. try
  156. {
  157. SqlDrConn.Open();
  158. SqlCommand SqlCmd = new SqlCommand(StrSql, SqlDrConn);
  159. SqlDataReader SqlDr = SqlCmd.ExecuteReader();
  160. if (SqlDr.HasRows)
  161. {
  162. DataTable dt = new DataTable();
  163. //读取SqlDataReader里的内容
  164. dt.Load(SqlDr);
  165. //关闭对象和连接
  166. SqlDr.Close();
  167. SqlDrConn.Close();
  168. return dt;
  169. }
  170. return null;
  171. }
  172. catch (Exception ex)
  173. {
  174. return null;
  175. }
  176. finally
  177. {
  178. SqlDrConn.Close();
  179. }
  180. }
  181. }
  182. public static class test
  183. {
  184. public static void TestGet1()
  185. {
  186. for (int i = 1; i <= 2; ++i)
  187. {
  188. Stopwatch sw = new Stopwatch();
  189. sw.Start();
  190. var dt = ConnectionPool.getPool().GetDataReader("Select * from Users");
  191. foreach (DataRow dr in dt.Rows)
  192. {
  193. Console.WriteLine("ID:" + i + ",方法1姓名:" + dr[1]);
  194. }
  195. sw.Stop();
  196. Console.WriteLine("Without Pooling, first connection elapsed {0} ms", sw.ElapsedMilliseconds);
  197. sw.Reset();
  198. sw.Start();
  199. dt = ConnectionPool.getPool().GetDataReader("Select * from City");
  200. foreach (DataRow dr in dt.Rows)
  201. {
  202. Console.WriteLine("ID:" + i + ",方法1名称:" + dr[1]);
  203. }
  204. sw.Stop();
  205. Console.WriteLine("Without Pooling, average connection elapsed {0} ms", sw.ElapsedMilliseconds / 100);
  206. dt = ConnectionPool.getPool().GetDataReader("Select * from Province");
  207. foreach (DataRow dr in dt.Rows)
  208. {
  209. Console.WriteLine("ID:" + i + ",方法1震惊:" + dr[1]);
  210. }
  211. }
  212. }
  213. public static void TestGet2()
  214. {
  215. for (int i = 1; i <= 2; ++i)
  216. {
  217. var dt = ConnectionPool.getPool().GetDataReader("Select * from Users");
  218. foreach (DataRow dr in dt.Rows)
  219. {
  220. Console.WriteLine("ID:" + i + ",方法2姓名:" + dr[1]);
  221. }
  222. dt = ConnectionPool.getPool().GetDataReader("Select * from City");
  223. foreach (DataRow dr in dt.Rows)
  224. {
  225. Console.WriteLine("ID:" + i + ",方法2名称:" + dr[1]);
  226. }
  227. dt = ConnectionPool.getPool().GetDataReader("Select * from Province");
  228. foreach (DataRow dr in dt.Rows)
  229. {
  230. Console.WriteLine("ID:" + i + ",方法2震惊:" + dr[1]);
  231. }
  232. }
  233. }
  234. public static void Gettest1()
  235. {
  236. //调用
  237. SqlConnection conn = null;
  238. string strkey = Guid.NewGuid().ToString();
  239. for (int i = 1; i <= 10; ++i)
  240. {
  241. //获取连接
  242. conn = ConnectionPool.getPool().getConnection(strkey);
  243. try
  244. {
  245. //数据操作
  246. SqlCommand cmd = new SqlCommand("Select * from Users", conn);
  247. SqlDataReader dr = cmd.ExecuteReader();
  248. while (dr.Read())
  249. {
  250. Console.WriteLine("ID:" + i + ",1姓名:" + dr[1]);
  251. }
  252. dr.Close();
  253. cmd = new SqlCommand("Select * from Province", conn);
  254. dr = cmd.ExecuteReader();
  255. while (dr.Read())
  256. {
  257. Console.WriteLine("ID:" + i + ",1名称:" + dr[1]);
  258. }
  259. dr.Close();
  260. //将连接添加回连接池中
  261. ConnectionPool.getPool().closeConnection(strkey, conn);
  262. }
  263. catch (Exception ex)
  264. {
  265. Console.WriteLine("\n异常信息:\n{0}", ex.Message);
  266. break;
  267. }
  268. }
  269. ConnectionPool.getPool().Close(strkey);
  270. }
  271. public static void Gettest2()
  272. {
  273. //调用
  274. SqlConnection conn = null;
  275. string strkey = Guid.NewGuid().ToString();
  276. for (int i = 11; i <= 20; ++i)
  277. {
  278. //获取连接
  279. conn = ConnectionPool.getPool().getConnection(strkey);
  280. try
  281. {
  282. //数据操作
  283. SqlCommand cmd = new SqlCommand("Select * from Users", conn);
  284. SqlDataReader dr = cmd.ExecuteReader();
  285. while (dr.Read())
  286. {
  287. Console.WriteLine("ID:" + i + ",2姓名:" + dr[1]);
  288. }
  289. dr.Close();
  290. cmd = new SqlCommand("Select * from Province", conn);
  291. dr = cmd.ExecuteReader();
  292. while (dr.Read())
  293. {
  294. Console.WriteLine("ID:" + i + ",2名称:" + dr[1]);
  295. }
  296. dr.Close();
  297. //将连接添加回连接池中
  298. ConnectionPool.getPool().closeConnection(strkey, conn);
  299. }
  300. catch (Exception ex)
  301. {
  302. Console.WriteLine("\n异常信息:\n{0}", ex.Message);
  303. break;
  304. }
  305. }
  306. ConnectionPool.getPool().Close(strkey);
  307. }
  308. public static void Gettest3()
  309. {
  310. List<DataTable> collection = new List<DataTable>();
  311. try
  312. {
  313. for (int i = 20001; i <= 500000; i++)
  314. {
  315. var conns = ConnectionPool.getPools();
  316. var str = conns.getConn();
  317. string strsql = @"INSERT INTO [Chloe].[dbo].[Users]
  318. ([Name]
  319. ,[Gender]
  320. ,[Age]
  321. ,[CityId]
  322. ,[OpTime])
  323. VALUES
  324. ('jjg" + i + @"'
  325. ," + i + 1 + @"
  326. ," + i + 2 + @"
  327. ," + i + 3 + @"
  328. ,'" + DateTime.Now + @"')";
  329. str.Open();
  330. SqlCommand SqlCmd = new SqlCommand(strsql, str);
  331. var num = SqlCmd.ExecuteNonQuery();
  332. Console.WriteLine("ID:" + i + ",保存状态:" + num);
  333. }
  334. for (int i = 1; i <= 200000; ++i)
  335. {
  336. var conns = ConnectionPool.getPools();
  337. var str = conns.getConn();
  338. if (str.State != ConnectionState.Open)
  339. {
  340. str.Open();
  341. SqlCommand SqlCmd = new SqlCommand("Select * from Users", str);
  342. SqlDataReader SqlDr = SqlCmd.ExecuteReader();
  343. if (SqlDr.HasRows)
  344. {
  345. DataTable dt = new DataTable();
  346. //读取SqlDataReader里的内容
  347. dt.Load(SqlDr);
  348. collection.Add(dt);
  349. }
  350. }
  351. Console.WriteLine("ID:" + i + ",打开数据库状态:" + str.State);
  352. }
  353. }
  354. catch (Exception ex)
  355. {
  356. Console.WriteLine(ex.ToString());
  357. }
  358. Console.WriteLine("总共创建了对象:" + collection.Count);
  359. Console.Write("请按任意键继续");
  360. Console.ReadLine();
  361. }
  362. /// <summary>
  363. ///
  364. /// </summary>
  365. /// <param name="sql"></param>
  366. public static void ExecuteDataReader(string sql)
  367. {
  368. }
  369. }
  370. }