创建一个连接池操作类

  1. using MySql.Data.MySqlClient;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Timers;
  7.  
  8. namespace CommonAssistant
  9. {
  10.  
  11. public class MySqlConnectionPool
  12. {
  13. private readonly string sqlConnect = string.Empty;
  14. public MySqlConnectionPool(string Connection)
  15. {
  16. sqlConnect = Connection;
  17.  
  18. //定时器轮询连接,清理不在使用的连接
  19. var timer = new Timer();
  20. timer.Enabled = true;
  21. timer.Elapsed += (a, b) =>
  22. {
  23. //轮询连接池连接,删除满足条件的连接
  24. delwithConnectPool("remove");
  25. Console.WriteLine( "连接数:"+getCount());
  26.  
  27. };
  28. timer.Interval = * ; //10分钟一次
  29. timer.AutoReset = true;//一直执行
  30. }
  31.  
  32. private static List<ConnectionItem> listConnects = new List<ConnectionItem>();
  33.  
  34. private static readonly object obj_getConnects = new object();
  35. public Tuple<bool, ConnectionItem> delwithConnectPool(string type)
  36. {
  37. //保证并发条件下集合增删改查时的数据唯一性
  38. lock (obj_getConnects)
  39. {
  40. bool result = false;
  41. ConnectionItem result_item = null;
  42. switch (type)
  43. {
  44. case "get":
  45. var connectItem = listConnects.Where(u => u.ifBusy == false).FirstOrDefault();
  46.  
  47. if (connectItem == null)
  48. {
  49. listConnects.Add(result_item = getInstance(sqlConnect));
  50. }
  51. else {
  52. if (connectItem.mySqlConn.State == System.Data.ConnectionState.Open)
  53. {
  54. connectItem.setBusy(true);
  55. connectItem.updateTime(DateTime.Now);
  56. result_item = connectItem;
  57. }
  58. else {
  59. listConnects.Add(result_item = getInstance(sqlConnect));
  60. }
  61. }
  62.  
  63. break;
  64. case "remove":
  65. if (listConnects != null && listConnects.Any())
  66. {
  67. //删除移除 超过10分钟未使用的的连接,使用两分钟的未释放连接,连接状态已关闭的连接
  68. var listOuteTimes = listConnects.Where(u => (u.ifBusy == true && (DateTime.Now - u.time).TotalSeconds > ) || ((DateTime.Now - u.time).TotalSeconds > * ) ||(u.mySqlConn.State != System.Data.ConnectionState.Open) );
  69. foreach (var item in listOuteTimes)
  70. {
  71. item.mySqlConn.Close();
  72. item.mySqlConn.Dispose();//释放
  73. }
  74. //超时连接移除
  75. listConnects.RemoveAll(u => (u.ifBusy == true && (DateTime.Now - u.time).TotalSeconds > ) || ((DateTime.Now - u.time).TotalSeconds > * ) || (u.mySqlConn.State != System.Data.ConnectionState.Open));
  76. }
  77. break;
  78. }
  79. return new Tuple<bool, ConnectionItem>(result, result_item);
  80. }
  81.  
  82. }
  83.  
  84. public ConnectionItem getInstance(string connect)
  85. {
  86.  
  87. var item = new ConnectionItem()
  88. {
  89.  
  90. ifBusy = true,
  91. time = DateTime.Now,
  92. mySqlConn = new MySqlConnection(connect)
  93. };
  94. item.mySqlConn.Open();
  95. return item;
  96.  
  97. }
  98.  
  99. //获取一个空闲连接
  100. public ConnectionItem getFreeConnectItem()
  101. {
  102. return delwithConnectPool("get").Item2;
  103. }
  104.  
  105. public int getCount() {
  106. return listConnects.Count;
  107. }
  108.  
  109. }
  110.  
  111. public class ConnectionItem : IDisposable
  112. {
  113. public DateTime time { get; set; }
  114.  
  115. public MySqlConnection mySqlConn { get; set; }
  116.  
  117. public bool ifBusy { get; set; }//设置是否在使用
  118. public void setBusy(bool busy)
  119. {
  120. ifBusy = busy;
  121. }
  122.  
  123. public void updateTime(DateTime dt)
  124. {
  125. time = dt;
  126. }
  127.  
  128. public void Dispose()
  129. {
  130. ifBusy = false;
  131. }
  132. }
  133. }

基于不同的mysql数据库,使用不同连接池

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4.  
  5. namespace CommonAssistant
  6. {
  7. public class WorkDbConnectManage
  8. {
  9. #region 连接池(1)
  10. private static MySqlConnectionPool tempPool_A = null;
  11. private static readonly string dbConnect_A = "Database=ywthgoods;Data Source=localhost;Port=3306;UserId=root;Password=123456;Charset=utf8;TreatTinyAsBoolean=false;Allow User Variables=True";
  12.  
  13. private static readonly object readPoolA = new object();
  14. public static MySqlConnectionPool getTempPool_A()
  15. {
  16. //双if加锁,有且只创建一个连接池
  17. if (tempPool_A == null)
  18. {
  19. lock (readPoolA)
  20. {
  21. if (tempPool_A == null)
  22. {
  23. tempPool_A = new MySqlConnectionPool(dbConnect_A);
  24. }
  25. }
  26. }
  27. return tempPool_A;
  28. }
  29.  
  30. public static ConnectionItem getWork1Conn_A()
  31. {
  32. return getTempPool_A().getFreeConnectItem();
  33.  
  34. }
  35. #endregion
  36.  
  37. #region 连接池(2)
  38. private static MySqlConnectionPool tempPool_B = null;
  39. private static readonly string dbConnect_B = "";
  40.  
  41. private static readonly object readPoolB_lock = new object();
  42. public static MySqlConnectionPool getTempPool_B()
  43. {
  44. //双if加锁,有且只创建一个连接池
  45. if (tempPool_B == null)
  46. {
  47. lock (readPoolB_lock)
  48. {
  49. if (tempPool_A == null)
  50. {
  51. tempPool_A = new MySqlConnectionPool(dbConnect_B);
  52. }
  53. }
  54. }
  55. return tempPool_A;
  56. }
  57.  
  58. public static ConnectionItem getWork1Conn_B()
  59. {
  60. return getTempPool_B().getFreeConnectItem();
  61.  
  62. }
  63. #endregion
  64.  
  65. }
  66. }

C# 基于创建一个mysql 连接池的更多相关文章

  1. JDBC创建mysql连接池代码

    1.底层实现类(DBConnection) package JDBC.JDBCPool.MyJDBCPool; import java.sql.Connection; import java.sql. ...

  2. Swoole4-swoole创建Mysql连接池

    一 .什么是mysql连接池 场景:每秒同时有1000个并发,但是这个mysql同时只能处理400个连接,mysql会宕机. 解决方案:连接池,这个连接池建立了200个和mysql的连接,这1000个 ...

  3. swoole4创建Mysql连接池

    一 .什么是mysql连接池 场景:每秒同时有1000个并发,但是这个mysql同时只能处理400个连接,mysql会宕机.   解决方案:连接池,这个连接池建立了200个和mysql的连接,这100 ...

  4. 实现一个协程版mysql连接池

    实现一个协程版的mysql连接池,该连接池支持自动创建最小连接数,自动检测mysql健康:基于swoole的chanel. 最近事情忙,心态也有点不积极.技术倒是没有落下,只是越来越不想写博客了.想到 ...

  5. nodejs + redis/mysql 连接池问题

    nodejs + redis/mysql 连接池问题 需不需要连接池 连接池的作用主要是较少每次临时建立连接所带来的开销.初步一看,nodejs运行单线程上,它不能同时使用多个连接,乍一看是不需要连接 ...

  6. MySQL连接池

    1. using System; using System.Collections; using MySql.Data.MySqlClient; namespace Helper { /// < ...

  7. python中实现mysql连接池

    python中实现mysql连接池 import pymysql from DBUtils.PooledDB import PooledDB MYSQL_HOST = 'localhost' USER ...

  8. workerman如何写mysql连接池

    首先要了解为什么用连接池,连接池能为你解决什么问题 连接池主要的作用1.减少与数据服务器建立TCP连接三次握手及连接关闭四次挥手的开销,从而降低客户端和mysql服务端的负载,缩短请求响应时间2.减少 ...

  9. Mysql 连接池

    数据库连接池的作用: 数据库连接池负责分配.管理和释放数据库连接,它允许应用程序重复使用一个现有的数据库连接,而不是再重新建立一个:释放空闲时间超过最大空闲时间的数据库连接来避免因为没有释放数据库连接 ...

随机推荐

  1. springMvc注册时图形验证码完整代码与详细步骤``````后续更新注册时对密码进行加密

      第一使用 画图软件制作图片 ,文件名就是验证码    ------用户的实体类 import java.util.Date; public class Member {    private in ...

  2. 快速调通支付宝当面付Demo

    1.访问如下地址: https://auth.alipay.com/login/ant_sso_index.htm?goto=https%3A%2F%2Fopenhome.alipay.com%2Fp ...

  3. document.readyState和document.DOMContentLoaded判断DOM的加载完成

    document.readyState:判断文档是否加载完成.firefox不支持. 这个属性是只读的,传回值有以下的可能: 0-UNINITIALIZED:XML 对象被产生,但没有任何文件被加载. ...

  4. 详解 MySQL int 类型的长度值问题

    以下是每个整数类型的存储和范围 (来自 mysql 手册)

  5. 开启.NET Core 3时代,DevExpress v19.2.5带你全新启航

    DevExpress Universal Subscription(又名DevExpress宇宙版或DXperience Universal Suite)是全球使用广泛的.NET用户界面控件套包,De ...

  6. Case Closed?

    Finally, we'll want a way to test whether a file we've opened is closed. Sometimes we'll have a lot ...

  7. 【leetcode】959. Regions Cut By Slashes

    题目如下: In a N x N grid composed of 1 x 1 squares, each 1 x 1 square consists of a /, \, or blank spac ...

  8. Delphi获取指定文件的版本号

    获取指定文件的版本号 方式一: function GetFileVersion(FileName: string): string; type PVerInfo = ^TVS_FIXEDFILEINF ...

  9. 学习Caffe(一)安装Caffe

    Caffe是一个深度学习框架,本文讲阐述如何在linux下安装GPU加速的caffe. 系统配置是: OS: Ubuntu14.04 CPU: i5-4690 GPU: GTX960 RAM: 8G ...

  10. 测试使用python的用途

    使用Python:1. 分析日志,尤其是服务器端日志.脚本就是短小精悍的2. 用来生成测试数据,比如生成随机的10w个词,很麻烦:如果找一个字库,存在数表里,然后用Python取数据3. 做数据发出的 ...