创建一个连接池操作类

using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers; namespace CommonAssistant
{ public class MySqlConnectionPool
{
private readonly string sqlConnect = string.Empty;
public MySqlConnectionPool(string Connection)
{
sqlConnect = Connection; //定时器轮询连接,清理不在使用的连接
var timer = new Timer();
timer.Enabled = true;
timer.Elapsed += (a, b) =>
{
//轮询连接池连接,删除满足条件的连接
delwithConnectPool("remove");
Console.WriteLine( "连接数:"+getCount()); };
timer.Interval = * ; //10分钟一次
timer.AutoReset = true;//一直执行
} private static List<ConnectionItem> listConnects = new List<ConnectionItem>(); private static readonly object obj_getConnects = new object();
public Tuple<bool, ConnectionItem> delwithConnectPool(string type)
{
//保证并发条件下集合增删改查时的数据唯一性
lock (obj_getConnects)
{
bool result = false;
ConnectionItem result_item = null;
switch (type)
{
case "get":
var connectItem = listConnects.Where(u => u.ifBusy == false).FirstOrDefault(); if (connectItem == null)
{
listConnects.Add(result_item = getInstance(sqlConnect));
}
else {
if (connectItem.mySqlConn.State == System.Data.ConnectionState.Open)
{
connectItem.setBusy(true);
connectItem.updateTime(DateTime.Now);
result_item = connectItem;
}
else {
listConnects.Add(result_item = getInstance(sqlConnect));
}
} break;
case "remove":
if (listConnects != null && listConnects.Any())
{
//删除移除 超过10分钟未使用的的连接,使用两分钟的未释放连接,连接状态已关闭的连接
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) );
foreach (var item in listOuteTimes)
{
item.mySqlConn.Close();
item.mySqlConn.Dispose();//释放
}
//超时连接移除
listConnects.RemoveAll(u => (u.ifBusy == true && (DateTime.Now - u.time).TotalSeconds > ) || ((DateTime.Now - u.time).TotalSeconds > * ) || (u.mySqlConn.State != System.Data.ConnectionState.Open));
}
break;
}
return new Tuple<bool, ConnectionItem>(result, result_item);
} } public ConnectionItem getInstance(string connect)
{ var item = new ConnectionItem()
{ ifBusy = true,
time = DateTime.Now,
mySqlConn = new MySqlConnection(connect)
};
item.mySqlConn.Open();
return item; } //获取一个空闲连接
public ConnectionItem getFreeConnectItem()
{
return delwithConnectPool("get").Item2;
} public int getCount() {
return listConnects.Count;
} } public class ConnectionItem : IDisposable
{
public DateTime time { get; set; } public MySqlConnection mySqlConn { get; set; } public bool ifBusy { get; set; }//设置是否在使用
public void setBusy(bool busy)
{
ifBusy = busy;
} public void updateTime(DateTime dt)
{
time = dt;
} public void Dispose()
{
ifBusy = false;
}
}
}

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

using System;
using System.Collections.Generic;
using System.Text; namespace CommonAssistant
{
public class WorkDbConnectManage
{
#region 连接池(1)
private static MySqlConnectionPool tempPool_A = null;
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"; private static readonly object readPoolA = new object();
public static MySqlConnectionPool getTempPool_A()
{
//双if加锁,有且只创建一个连接池
if (tempPool_A == null)
{
lock (readPoolA)
{
if (tempPool_A == null)
{
tempPool_A = new MySqlConnectionPool(dbConnect_A);
}
}
}
return tempPool_A;
} public static ConnectionItem getWork1Conn_A()
{
return getTempPool_A().getFreeConnectItem(); }
#endregion #region 连接池(2)
private static MySqlConnectionPool tempPool_B = null;
private static readonly string dbConnect_B = ""; private static readonly object readPoolB_lock = new object();
public static MySqlConnectionPool getTempPool_B()
{
//双if加锁,有且只创建一个连接池
if (tempPool_B == null)
{
lock (readPoolB_lock)
{
if (tempPool_A == null)
{
tempPool_A = new MySqlConnectionPool(dbConnect_B);
}
}
}
return tempPool_A;
} public static ConnectionItem getWork1Conn_B()
{
return getTempPool_B().getFreeConnectItem(); }
#endregion }
}

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. Django框架(十八)—— CBV源码分析、restful规范、restframework框架

    目录 CBV源码分析.restful规范.restframework框架 一.CBV源码分析 1.url层的使用CBV 2.as_view方法 3.view方法 4.dispatch方法(可以在视图层 ...

  2. Scrapy框架: middlewares.py设置

    # -*- coding: utf-8 -*- # Define here the models for your spider middleware # # See documentation in ...

  3. OpenSuSe开启sshd服务

    需要测试OpenSuSE11 x64上mysql性能,发现很多东西与centos以及红帽有差别.其中最切身的就是sshd服务的开启. 安装好OpenSuSE 11后,发现ssh连接不上去,可以ping ...

  4. 4、服务注册&服务提供者

    1.什么是服务提供者 服务提供者(Service Provider):是指服务的被调用方(即:为其它服务提供服务的服务):服务提供者,作为一个Eureka Client,向Eureka Server做 ...

  5. 提交disable的Select值到后台

    需求:界面上把select控件disable,然后将默认值传到后台 问题1:select disable: js中可以这样写: document.getElementById("provin ...

  6. myeclipse中出现The method xxx of type must override or implement a supertype

    出现问题提示:The method xxx of type must override or implement a supertype? annotation:@Override的原因 查阅了一下资 ...

  7. RK3288编译 Android 5.1 固件

    1 准备工作 编译 Android 对机器的配置要求较高: 64 位 CPU 16GB 物理内存+交换内存 30GB 空闲的磁盘空间用于构建,源码树另外占用大约 25GB Ubuntu 14.04 操 ...

  8. 第五章 配置私有仓库Harbor

    一.Harbor 安装(尚硅谷资料) 安装:Harbor 官方地址:官方地址:https://github.com/vmware/harbor/releases 1.解压软件包 tar xvf har ...

  9. favicon.ico引用

    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"> ...

  10. final关键字和static关键字

    final关键字:最终态--修饰成员变量,成员方法,类 final修饰变量: 基本类型变量:该变量为常量不能被赋值 引用类型变量:该地址不能被概变 地址不能被概变的原因: final Student ...