linq2mysql连接池_C# 基于创建一个mysql 连接池

usingMySql.Data.MySqlClient;usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Timers;namespaceCommonAssistant

{public classMySqlConnectionPool

{private readonly string sqlConnect = string.Empty;public MySqlConnectionPool(stringConnection)

{

sqlConnect=Connection;//定时器轮询连接,清理不在使用的连接

var timer = newTimer();

timer.Enabled= true;

timer.Elapsed+= (a, b) =>{//轮询连接池连接,删除满足条件的连接

delwithConnectPool("remove");

Console.WriteLine("连接数:"+getCount());

};

timer.Interval= 1000 * 10; //10分钟一次

timer.AutoReset = true;//一直执行

}private static List listConnects = new List();private static readonly object obj_getConnects = new object();public Tuple delwithConnectPool(stringtype)

{//保证并发条件下集合增删改查时的数据唯一性

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 > 120) || ((DateTime.Now - u.time).TotalSeconds > 60 * 10) ||(u.mySqlConn.State !=System.Data.ConnectionState.Open) );foreach (var item inlistOuteTimes)

{

item.mySqlConn.Close();

item.mySqlConn.Dispose();//释放

}//超时连接移除

listConnects.RemoveAll(u => (u.ifBusy == true && (DateTime.Now - u.time).TotalSeconds > 120) || ((DateTime.Now - u.time).TotalSeconds > 60 * 10) || (u.mySqlConn.State !=System.Data.ConnectionState.Open));

}break;

}return new Tuple(result, result_item);

}

}public ConnectionItem getInstance(stringconnect)

{var item = newConnectionItem()

{

ifBusy= true,

time=DateTime.Now,

mySqlConn= newMySqlConnection(connect)

};

item.mySqlConn.Open();returnitem;

}//获取一个空闲连接

publicConnectionItem getFreeConnectItem()

{return delwithConnectPool("get").Item2;

}public intgetCount() {returnlistConnects.Count;

}

}public classConnectionItem : IDisposable

{public DateTime time { get; set; }public MySqlConnection mySqlConn { get; set; }public bool ifBusy { get; set; }//设置是否在使用

public void setBusy(boolbusy)

{

ifBusy=busy;

}public voidupdateTime(DateTime dt)

{

time=dt;

}public voidDispose()

{

ifBusy= false;

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值